首次提交:初始化项目代码

This commit is contained in:
sunct
2026-07-31 15:18:32 +08:00
commit d6393266b0
193 changed files with 14287 additions and 0 deletions
+51
View File
@@ -0,0 +1,51 @@
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())
}
}