在 Go 语言中,如果你有一个接口类型的变量,并且你知道它的具体实现类型,你可以使用类型断言将其转换为具体类型。类型断言的语法是 value, ok := interfaceVar.(ConcreteType),其中 interfaceVar 是接口变量,ConcreteType 是具体类型。
package main
import (
"fmt"
)
// 定义一个接口
type Animal interface {
Speak() string
}
// 定义一个具体类型
type Dog struct {
Name string
}
// 实现接口方法
func (d Dog) Speak() string {
return "Woof!"
}
func main() {
// 创建一个 Dog 的实例,并将其赋值给接口类型的变量
var animal Animal = Dog{Name: "Buddy"}
// case2:
animalb := Animal(Dog{Name: "Buddy"})
fmt.Printf("This animal is saying: %s\n", animalb.Speak())
// 使用类型断言将接口变量转换为具体类型
if dog, ok := animal.(Dog); ok {
fmt.Printf("This is a Dog named %s and it says: %s\n", dog.Name, dog.Speak())
} else {
fmt.Println("The interface does not hold a Dog type")
}
}