Files
bulma/escape/slice_map_escape.go
T

46 lines
1.0 KiB
Go

package main
import "fmt"
type Person3 struct {
Name string
Age int
}
// sliceEscape 切片元素为指针,且切片被返回,元素逃逸
func sliceEscape() []*Person3 {
var people []*Person3
for i := 0; i < 3; i++ {
person := &Person3{Name: fmt.Sprintf("Person3%d", i), Age: 20 + i}
people = append(people, person) // person 逃逸
}
return people
}
// dynamicSlice 切片动态扩容,底层数组逃逸
func dynamicSlice() []int {
s := make([]int, 0) // 编译期无法确定最终容量
for i := 0; i < 100; i++ {
s = append(s, i) // 扩容时底层数组逃逸
}
return s
}
// mapEscape 映射值为指针,值逃逸
func mapEscape() map[string]*Person3 {
m := make(map[string]*Person3)
m["alice"] = &Person3{Name: "Alice", Age: 25} // 指针值逃逸
return m
}
func main() {
people := sliceEscape()
fmt.Printf("切片元素逃逸:%d个Person\n", len(people))
s := dynamicSlice()
fmt.Printf("切片扩容逃逸:len=%d, cap=%d\n", len(s), cap(s))
m := mapEscape()
fmt.Printf("映射值逃逸:%+v\n", *m["alice"])
}