填充未导出的字段

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

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}
}

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:

确定