52 lines
907 B
Go
52 lines
907 B
Go
package main
|
|
|
|
import "fmt"
|
|
|
|
// Animal 接口定义
|
|
type Animal interface {
|
|
Speak() string
|
|
}
|
|
|
|
// Dog 实现Animal接口
|
|
type Dog struct{}
|
|
|
|
func (d Dog) Speak() string {
|
|
return "汪汪汪"
|
|
}
|
|
|
|
// Cat 实现Animal接口
|
|
type Cat struct{}
|
|
|
|
func (c Cat) Speak() string {
|
|
return "喵喵喵"
|
|
}
|
|
|
|
// interfaceEscape 变量赋值给接口,触发逃逸
|
|
func interfaceEscape(animalType string) Animal {
|
|
var a Animal
|
|
if animalType == "dog" {
|
|
d := Dog{} // d 逃逸至堆
|
|
a = d
|
|
} else {
|
|
c := Cat{} // c 逃逸至堆
|
|
a = c
|
|
}
|
|
return a
|
|
}
|
|
|
|
// interfacePointer 指针赋值给接口,触发逃逸
|
|
func interfacePointer() interface{} {
|
|
p := &Dog{} // p 逃逸至堆
|
|
return p
|
|
}
|
|
|
|
func main() {
|
|
animal := interfaceEscape("dog")
|
|
fmt.Printf("接口动态派发:%s\n", animal.Speak())
|
|
|
|
iface := interfacePointer()
|
|
if dog, ok := iface.(*Dog); ok {
|
|
fmt.Printf("接口指针逃逸:%s\n", dog.Speak())
|
|
}
|
|
}
|