是否可以通过接口使用它?

问题描述 投票:0回答:1

为什么当我添加“ 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)
go types interface
1个回答
0
投票

类型Pet在声明为[]string时,无法使用类型Cat的值进行初始化,因为Catstring是不同的类型。这就是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方法,则必须使用接口进行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.