英文:
Populating unexported fields
问题
我正在使用以下带有停止逻辑的重试代码:https://upgear.io/blog/simple-golang-retry-function/
我的代码如下所示:
type Stop struct {
error
}
...
if s, ok := err.(Stop); ok {
return s.error
}
...
我试图使停止功能在命名空间之外起作用,所以我做了以下更改:
...
return lib.Stop{errors.New("this is an error")}
...
但是我遇到了一个编译错误:
implicit assignment to unexported field error in struct literal of type lib.Stop
当字段未导出时,我该如何填充Stop结构体中的错误?
我在考虑是否需要将结构体更改为Error error
,但这样就无法与err.(Stop)
配合使用了。
有什么想法如何解决这个问题吗?
英文:
I'm using this retry logic with a stop
https://upgear.io/blog/simple-golang-retry-function/
My code looks like this
type Stop struct {
error
}
...
if s, ok := err.(Stop); ok {
return s.error
}
...
I'm trying to get the Stop functionality to work outside the namespace, so I'm doing this
...
return lib.Stop{errors.New("this is an error")}
...
But I'm getting a complication error:
implicit assignment to unexported field error in struct literal of type lib.Stop
How would I populate the Stop with the error when its unexported?
I was thinking that I need change the struct to Error error
but then it doesnt work with the err.(Stop)
Any ideas how to do this?
答案1
得分: 1
你可以将其更改为命名字段Err error
,然后显式添加Error() string
方法,使Stop
实现error
接口:
type Stop struct {
Err error
}
func (s Stop) Error() string {
return s.Err.Error()
}
或者,你可以为Stop
创建一个“构造函数”函数(这是让外部调用者实例化具有未导出字段的结构体的常用方法):
type Stop struct {
error
}
func NewStop(err error) Stop {
return Stop{err}
}
英文:
You could change it to a named field Err error
and then explicitly add the Error() string
method to make Stop
implement error
:
type Stop struct {
Msg error
}
func (s Stop) Error() string {
return s.Msg.Error()
}
Alternatively, you could just create a "constructor" func for Stop
(which is the general approach for letting outside callers instantiate a struct with unexported fields):
type Stop struct {
error
}
func NewStop(err error) Stop {
return Stop{err}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论