填充未导出的字段

huangapple go评论148阅读模式
英文:

Populating unexported fields

问题

我正在使用以下带有停止逻辑的重试代码:https://upgear.io/blog/simple-golang-retry-function/

我的代码如下所示:

  1. type Stop struct {
  2. error
  3. }
  4. ...
  5. if s, ok := err.(Stop); ok {
  6. return s.error
  7. }
  8. ...

我试图使停止功能在命名空间之外起作用,所以我做了以下更改:

  1. ...
  2. return lib.Stop{errors.New("this is an error")}
  3. ...

但是我遇到了一个编译错误:

  1. 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

  1. type Stop struct {
  2. error
  3. }
  4. ...
  5. if s, ok := err.(Stop); ok {
  6. return s.error
  7. }
  8. ...

I'm trying to get the Stop functionality to work outside the namespace, so I'm doing this

  1. ...
  2. return lib.Stop{errors.New("this is an error")}
  3. ...

But I'm getting a complication error:

  1. 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接口:

  1. type Stop struct {
  2. Err error
  3. }
  4. func (s Stop) Error() string {
  5. return s.Err.Error()
  6. }

或者,你可以为Stop创建一个“构造函数”函数(这是让外部调用者实例化具有未导出字段的结构体的常用方法):

  1. type Stop struct {
  2. error
  3. }
  4. func NewStop(err error) Stop {
  5. return Stop{err}
  6. }
英文:

You could change it to a named field Err error and then explicitly add the Error() string method to make Stop implement error:

  1. type Stop struct {
  2. Msg error
  3. }
  4. func (s Stop) Error() string {
  5. return s.Msg.Error()
  6. }

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):

  1. type Stop struct {
  2. error
  3. }
  4. func NewStop(err error) Stop {
  5. return Stop{err}
  6. }

huangapple
  • 本文由 发表于 2023年5月2日 22:48:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76156110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定