gpt4 book ai didi

go - 结构体在 Go 中包含接口(interface)时的 new 与 {}

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:30 25 4
gpt4 key购买 nike

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。

2年前关闭。




Improve this question




我有一个问题,就像下面的代码一样。

package main

type I interface {
Get()
}

type Animal struct{}

func (a *Animal) Get() {}

type Dog struct {
Animal
}

func main() {
var i I
i = new(Dog) // success
i = Dog{} // error
}

游乐场: https://play.golang.org/p/RT7egtDd5UV

输出:
./prog.go:18:4: cannot use Dog literal (type Dog) as type I in assignment:
Dog does not implement I (Get method has pointer receiver)

当我分配 inew() ,就是成功。但是当我使用 Dog{} ,失败了。所以我想知道这是为什么?

最佳答案

Animal满足Ifunc (a *Animal) Get() {}它需要一个指针接收器。
new(Dog)返回一个指针。使用 &Dog{}返回一个指针。

例如,

package main

type I interface {
Get()
}

type Animal struct{}

func (a *Animal) Get() {}

type Dog struct {
Animal
}

func main() {
var i I
i = new(Dog) // success
i = &Dog{} // success
_ = i
}

游乐场: https://play.golang.org/p/i8GF8JSzm5w

关于go - 结构体在 Go 中包含接口(interface)时的 new 与 {},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57504781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com