您绝对可以做到,其中一种方法是使用类型断言,如另一个答案here 所示。否则@Himanshu here 的回答很好地描述了这种情况。
我想加入讨论以进一步描述您的方式
可以有一个结构遵循一个接口,也可以定义它自己的方法
MakeDog 方法返回一个 Animal,有很多原因您可以考虑直接返回一个 Dog(或任何具体类型)。
之所以提出这个问题,是因为当我第一次开始用 Go 编程时,有人告诉我有关创建方法的事情:
接受一个接口并返回一个具体类型(例如结构)
接口可以接受任何具体类型。这就是为什么当您不知道要传递给函数的参数类型时使用它们的原因。
我用以下术语进行了谷歌搜索,发现了很多文章
golang 接受接口,返回结构体
例如:https://mycodesmells.com/post/accept-interfaces-return-struct-in-go 和 http://idiomaticgo.com/post/best-practice/accept-interfaces-return-structs/
我已经整理了一些演示,扩展了您在问题中的概念,以尝试清楚地描述接口方法以及特定类型的方法和属性
取自this snippet on Playground
package main
import (
"fmt"
)
type Animal interface {
MakeNoise() string
}
// printNoise accepts any animal and prints it's noise
func printNoise(a Animal) {
fmt.Println(a.MakeNoise())
}
type pet struct {
nLegs int
color string
}
// describe is available to all types of Pet, but not for an animal
func (p pet) describe() string {
return fmt.Sprintf(`My colour is "%s", and I have "%d" legs`, p.color, p.nLegs)
}
type Dog struct {
pet
favouriteToy string
}
// MakeNoise implements the Animal interface for type Dog
func (Dog) MakeNoise() string {
return "Bark!"
}
// WagTail is something only a Dog can do
func (d Dog) WagTail() {
fmt.Println("I am a dog,", d.pet.describe(), ": Wags Tail")
}
type Cat struct {
pet
favouriteSleepingPlace string
}
// MakeNoise implements the Animal interface for type Cat
func (Cat) MakeNoise() string {
return "Meow!"
}
// ArchBack is something only a Cat can do
func (c Cat) ArchBack() {
fmt.Println("I am a cat,", c.pet.describe(), ": Arches Back")
}
type Bird struct {
pet
favoritePerch string
}
// MakeNoise implements the Animal interface for type Cat
func (Bird) MakeNoise() string {
return "Tweet!"
}
// Hop is something only a Bird can do
func (c Bird) Hop() {
fmt.Println("I am a bird,", c.pet.describe(), ": Hops to a different perch")
}
func main() {
dog := Dog{
pet: pet{nLegs: 4, color: "Brown"},
favouriteToy: "Ball",
}
printNoise(dog)
dog.WagTail()
cat := Cat{
pet: pet{nLegs: 4, color: "Tabby"},
favouriteSleepingPlace: "Sofa",
}
printNoise(cat)
cat.ArchBack()
bird := Bird{
pet: pet{nLegs: 2, color: "Rainbow"},
favoritePerch: "Back of Cage",
}
printNoise(bird)
bird.Hop()
}