我正在尝试理解 Go 中的接口(interface)。我写了这个:
package main
import "fmt"
type Animal struct {
Name string
Ability string
}
type AbilityShower interface {
ShowAbility() string
}
func (a Animal) ShowAbility() string {
return fmt.Sprintf("%s can %s", a.Name, a.Ability)
}
func main() {
var Dog Animal = Animal{
Name: "Dog",
Ability: "Walk",
}
Dog.ShowAbility()
}
但是当我使用 go run main.go
运行时,控制台中什么也没有出现。我做错了什么?
最佳答案
您没有打印结果。将主要更改为
func main() {
var Dog Animal = Animal{
Name: "Dog",
Ability: "Walk",
}
fmt.Println(Dog.ShowAbility())
}
仅供引用:fmt.Sprintf() 返回一个字符串并且不会将其打印到标准输出
// Sprintf formats according to a format specifier and returns the resulting string.
关于function - 了解 Golang 中的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48859574/