大家好,今天本人给大家带来文章《如何在 Go 中为接口分配指针》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
package main
import "fmt"
type intr interface {
String() string
}
type bar struct{}
func (b *bar) String() string {
return "bar"
}
type foo struct {
bar *intr
}
func main() {
bar1 := bar{}
foo1 := foo{bar: &bar1}
fmt.Println(foo1)
}
我收到编译时错误:
不能在字段值中使用 &bar1(类型 *bar)作为类型 *intr:*intr 是指向接口的指针,而不是接口
为什么会出现这个错误?
如何分配foo.bar?
解决方案
您将其分配给接口的指针。将字段类型更改为接口后,它将起作用:
type foo struct {
bar intr
}
很少需要接口指针。
终于介绍完啦!小伙伴们,这篇关于《如何在 Go 中为接口分配指针》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
