【发布时间】:2020-05-15 12:35:49
【问题描述】:
编辑:这不是在 Go 中使用接口的正确方式。这个问题的目的是让我了解 Go 中的空接口是如何工作的。
如果 Go 中的所有类型都实现了interface{}(空接口),为什么我不能访问Cat 和Dog 结构中的name 字段?如何通过函数 sayHi() 访问每个结构的名称字段?
package main
import (
"fmt"
)
func sayHi(i interface{}) {
fmt.Println(i, "says hello")
// Not understanding this error message
fmt.Println(i.name) // i.name undefined (type interface {} is interface with no methods)
}
type Dog struct{
name string
}
type Cat struct{
name string
}
func main() {
d := Dog{"Sparky"}
c := Cat{"Garfield"}
sayHi(d) // {Sparky} says hello
sayHi(c) // {Garfield} says hello
}
【问题讨论】:
-
经过进一步研究,我发现这是通过 A Tour of Go 进行的。 tour.golang.org/methods/15.
-
接口指定行为(读取方法),而不是数据。
标签: go go-interface