【发布时间】:2020-02-07 02:32:46
【问题描述】:
我正在尝试理解 Golang (1.12) 接口。我发现接口指针必须显式取消引用,这与结构不同:
import "fmt"
// A simple interface with one function
type myinter interface {
hello()
}
// Implement myinter
type mystruct struct {}
func (mystruct) hello() {
fmt.Println("I am T!")
}
// Some function that calls the hello function as defined by myinter
func callHello(i *myinter) {
i.hello() // <- cannot resolve reference 'hello'
}
func main() {
newMystruct := &mystruct{}
callHello(newMystruct)
}
在这里,我的callHello 函数无法解析对接口中定义的hello 函数的引用。当然,取消引用接口是可行的:
func callHello(i *myinter) {
(*i).hello() // <- works!
}
但是在结构体中,我们可以直接调用函数,none of this cumbersome dereference notation is necessary:
func callHello(s *mystruct) {
s.hello() // <- also works!
}
为什么会这样?为什么我们必须显式取消引用interface 指针? Go 是否试图阻止我将 interface 指针传递给函数?
【问题讨论】:
-
Go 中很少使用指向接口的指针。问题中没有任何内容表明有理由使用指向接口的指针。通过将
*myinter更改为myinter进行修复。这修复了callHello(newMystruct)和i.hello()的错误。
标签: function go struct parameters interface