为什么添加 type 时以下内容有效,Pet []interface{Name()}但添加 type 时无效Pet []string?是否可以在不使用界面的情况下使其工作?package mainimport "fmt"type Pet []string // cannot use Cat("Puss") (type Cat) as type string in array or slice literal// type Pet []interface{Name()} // prt Fluffytype Cat stringfunc (c Cat) Name() { fmt.Println(c)}func main() { p := Pet{Cat("Whiskers"), Cat("Fluffy")} p1 := p[1] p1.Name() }./oo3.go:15:14: cannot use Cat("Whiskers") (type Cat) as type string in array or slice literal./oo3.go:15:31: cannot use Cat("Fluffy") (type Cat) as type string in array or slice literal./oo3.go:17:4: p1.Name undefined (type string has no field or method Name)
1 回答
翻翻过去那场雪
TA贡献2065条经验 获得超14个赞
type Pet,当声明为 a 时[]string,不能用 type 的值初始化Cat,因为Cat和string是不同的类型。这就是 Go 类型系统的工作原理。当您将新类型定义为type name otherType时,name将成为具有与基础类型相同内存布局的全新类型。例如,新类型不会有任何为otherType. 但是,您可以将 a 转换Cat为字符串:
p := Pet{string(Cat("Whiskers")), string(Cat("Fluffy"))}然后Pet仍然是一个字符串数组。
当你用方法定义Pet为接口数组时,现在可以用来初始化 的元素,因为实现了方法。NameCatPetCatName
简而言之:Petas a[]string仅保存字符串值。Petas a[]interface{Name{}}保存任何实现该Name方法的值。如果您需要Name在元素上调用方法Pet,那么您必须使用接口来完成。
- 1 回答
- 0 关注
- 132 浏览
添加回答
举报
0/150
提交
取消
