interface
行为定义 / Behavior Definition
go
type Speaker interface {
Speak() string
}类型判断 / Type Assertion & Type Switch
go
var s Speaker = Person{Name: "Bob"}
if p, ok := s.(Person); ok {
fmt.Println("It's a Person:", p.Name)
}
switch v := s.(type) {
case Person:
fmt.Println("Person:", v.Name)
default:
fmt.Println("Unknown type")
}没有 *
interface 是一个“装对象的盒子(引用容器)”
go
type A interface {
Foo()
}
type B struct {}
func (b *B) Foo() {}
func main() {
var a A = &B{}
a.Foo() // ✅
}var a A 没有 *
