是否可以在不使用界面的情况下使其工作?

Tom*_*m L -1 types interface go

为什么添加 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)
Run Code Online (Sandbox Code Playgroud)

Bur*_*dar 5

类型Pet,当声明为 a 时[]string,不能用 type 的值初始化Cat,因为Catstring是不同的类型。这就是 Go 类型系统的工作原理。当您将新类型定义为 时type name otherTypename将成为具有与基础类型相同的内存布局的全新类型。例如,新类型不会为 定义任何方法otherType。但是,您可以将 a 转换Cat为字符串:

    p := Pet{string(Cat("Whiskers")), string(Cat("Fluffy"))} 
Run Code Online (Sandbox Code Playgroud)

然后Pet仍然是一个字符串数组。

当你PetName方法定义为接口数组时,那么Cat现在可以用来初始化 的元素Pet,因为Cat实现了Name方法。

简而言之:Petas a[]string只保存字符串值。Petas a[]interface{Name{}}包含实现该Name方法的任何值。如果您需要NamePet元素上调用方法,那么您必须使用接口来完成。