当前位置: > > > > Go 中不能使用指向接口类型的指针吗?
来源:stackoverflow
2024-04-23 08:24:34
0浏览
收藏
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天给大家整理了《Go 中不能使用指向接口类型的指针吗?》,聊聊,我们一起来看看吧!
问题内容
我用di编写的代码如下。有2个代码。一个用于 use case
,另一个是 controller
,依赖于该 use case
。
- 用例
package usecase import "fmt" type interface interface { echo() string } type usecase struct {} func (u *usecase) echo() string { return fmt.sprintf("this is usecase!") }
- 控制器
package controller import ( "my-project/usecase" ) type controller struct { usecase *usecase.interface } func newcontroller(usecase *usecase.interface) *controller { return &controller{ usecase: usecase, } } func (s *controller) hello() { result := s.usecase.echo() println(result) }
但是,在控制器中显示了以下错误消息。
未解析的参考“echo”
控制器结构体controller
中字段usecase
的类型为*usecase.interface
。 (指针) 原因是实现该接口的usecase
的echo()
方法是一个指针接收者。
我不能像下面这样使用指向接口的指针?
type Controller struct { usecase *usecase.Interface }
解决方案
将代码更改为:
type controller struct { usecase usecase.interface } func newcontroller(usecase usecase.interface) *controller { return &controller{ usecase: usecase, } } func (s *controller) hello() { result := s.usecase.echo() println(result) }
几乎没有任何理由使用指向接口的指针。唯一需要指向接口的指针的时候是需要设置接口值(该值作为函数参数传递)时。即:
var x SomeInterface SetX(&x)
今天关于《Go 中不能使用指向接口类型的指针吗?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!