How to implement both fmt.Stringer and error interface on a type?

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

How to implement both fmt.Stringer and error interface on a type?

问题

fmt.Stringer 类似,fmt 包在打印值时会查找 error 接口。如果一个 类型 同时满足这两个接口,fmt 只会查找 error 而不是 Stringer。为什么会这样?我如何在一个类型上同时实现 Stringererror 接口?

英文:

As with fmt.Stringer, the fmt package looks for the error interface when printing values. In case if a type satisfies both interfaces, fmt only on look for error not Stringer. Why? How I could implement both Stringer and error on a type?

答案1

得分: 2

并不是一个通用解决方案,但在某些情况下,可以使用指针和非指针接收器来实现这个技巧:https://play.golang.org/p/DY4Cq4efsT

英文:

Not really a universal solution, but in certain situations one can use pointer vs non-pointer receivers to do the trick: https://play.golang.org/p/DY4Cq4efsT

huangapple
  • 本文由 发表于 2017年1月28日 18:29:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/41908709.html
匿名

发表评论

匿名网友

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

确定