package main
import (
"fmt"
)
func main() {
filtered := make([]*student, 10)
fmt.Printf("filtered: len=%v cap=%v \n", len(filtered), cap(filtered))
for index, val := range filtered {
fmt.Println("index: ", index, "val: ", val)
}
}
输出:
filtered: len=10 cap=10
index: 0 val: <nil>
index: 1 val: <nil>
index: 2 val: <nil>
index: 3 val: <nil>
index: 4 val: <nil>
index: 5 val: <nil>
index: 6 val: <nil>
index: 7 val: <nil>
index: 8 val: <nil>
index: 9 val: <nil>
可以看到filtered长度不为0,for循环就会遍历。不指定cap时,默认len和cap相等。
package main
import (
"fmt"
)
func main() {
filtered := make([]*student, 10)
fmt.Printf("filtered: len=%v cap=%v \n", len(filtered), cap(filtered))
for index, val := range filtered {
fmt.Println("index: ", index, "val: ", val)
filtered[index] = &student{
ID: index,
Name: fmt.Sprintf("%v", index),
}
}
fmt.Printf("filter[8]=%v, addr=%p\n", filtered[8], &filtered[8])
aa := filtered[8]
fmt.Printf("aa=%v, addr=%p\n", aa, &aa)
aa.Name = "test coderaction"
fmt.Printf("filter[8]=%v, addr=%p\n", filtered[8], &filtered[8])
fmt.Printf("aa=%v, addr=%p\n", aa, &aa)
}
type student struct {
ID int
Name string
}
func getPods() []*student {
stu1 := &student{
ID: 1,
Name: "stu1",
}
stu2 := &student{
ID: 2,
Name: "stu2",
}
return []*student{stu1, stu2}
}
输出:
filtered: len=10 cap=10
index: 0 val: <nil>
index: 1 val: <nil>
index: 2 val: <nil>
index: 3 val: <nil>
index: 4 val: <nil>
index: 5 val: <nil>
index: 6 val: <nil>
index: 7 val: <nil>
index: 8 val: <nil>
index: 9 val: <nil>
filter[8]=&{8 8}, addr=0xc0000a4040
aa=&{8 8}, addr=0xc00009c020
filter[8]=&{8 test coderaction}, addr=0xc0000a4040
aa=&{8 test coderaction}, addr=0xc00009c020
可以看到修改了aa之后,filtered[8]的内容也变掉了。
给aa新赋值&student{},发现filtered[8]是没有变化的:
package main
import (
"fmt"
)
func main() {
filtered := make([]*student, 10)
fmt.Printf("filtered: len=%v cap=%v \n", len(filtered), cap(filtered))
for index, val := range filtered {
fmt.Println("index: ", index, "val: ", val)
filtered[index] = &student{
ID: index,
Name: fmt.Sprintf("%v", index),
}
}
fmt.Printf("filter[8]=%v, addr=%p\n", filtered[8], &filtered[8])
aa := filtered[8]
fmt.Printf("aa=%v, addr=%p\n", aa, &aa)
aa = &student{
ID: 1001,
Name: "aaaa",
}
fmt.Printf("filter[8]=%v, addr=%p\n", filtered[8], &filtered[8])
fmt.Printf("aa=%v, addr=%p\n", aa, &aa)
}
type student struct {
ID int
Name string
}
可以看到aa的地址和filtered[8]不一样:
filtered: len=10 cap=10
index: 0 val: <nil>
index: 1 val: <nil>
index: 2 val: <nil>
index: 3 val: <nil>
index: 4 val: <nil>
index: 5 val: <nil>
index: 6 val: <nil>
index: 7 val: <nil>
index: 8 val: <nil>
index: 9 val: <nil>
filter[8]=&{8 8}, addr=0xc000090040
aa=&{8 8}, addr=0xc000006030
filter[8]=&{8 8}, addr=0xc000090040
aa=&{1001 aaaa}, addr=0xc000006030