为什么当我添加“ type Pet [] interface {Name()}”而不是当我添加“ type Pet [] string”时不起作用?是否可以通过界面使用它?
package main
import "fmt"
type Pet []string // cannot use Cat("Puss") (type Cat) as type string in array or slice literal
// type Pet []interface{Name()} // prt Fluffy
type Cat string
func (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)
类型Pet
在声明为[]string
时,无法使用类型Cat
的值进行初始化,因为Cat
和string
是不同的类型。这就是Go类型系统的工作方式。当您将新类型定义为type name otherType
时,name
成为一种全新的类型,其存储布局与基础类型相同。例如,新类型将没有为otherType
定义的任何方法。但是,您可以将Cat
转换为字符串:
p := Pet{string(Cat("Whiskers")), string(Cat("Fluffy"))}
然后Pet
仍然是字符串数组。
[当使用Pet
方法将Name
定义为接口数组时,由于Cat
实现了Pet
方法,因此Cat
现在可用于初始化Name
的元素。
因此简而言之:Pet
作为[]string
仅保存字符串值。 Pet
作为[]interface{Name{}}
包含实现Name
方法的任何值。如果需要在Name
元素上调用Pet
方法,则必须使用接口进行此操作。