我阅读了这篇文章并决定自己重复这种行为并进行实验:
package main
import (
"fmt"
"time"
)
type User struct {
i int
token string
}
func NewUser(i int, token string) User {
user := User{token: fmt.Sprint(i), i: i}
return user
}
func (u *User) PrintAddr() {
fmt.Printf("%d (PrintAddr): %p\n", u.i, u)
}
func main() {
users := make([]User, 4)
for i := 0; i < 4; i++ {
user := NewUser(i, "")
users[i] = user
}
for i, user := range users {
go user.PrintAddr()
go users[i].PrintAddr()
}
time.Sleep(time.Second)
}
(游乐场)
这是代码输出:
1 (PrintAddr): 0xc000056198
2 (PrintAddr): 0xc0000561b0
0 (PrintAddr): 0xc000056180
3 (PrintAddr): 0xc00000c030
3 (PrintAddr): 0xc00000c030
3 (PrintAddr): 0xc00000c030
3 (PrintAddr): 0xc00000c030
3 (PrintAddr): 0xc0000561c8
我也不明白,为什么 4 of 5 3 (PrintAddr)
are 0xc00000c030
,最后一个不一样?
但是,如果我使用指针数组而不是值数组,像这样,
func NewUser(i int, token string) *User {
user := &User{token: fmt.Sprint(i), i: i}
return user
}
// -snip-
func main() {
users := make([]*User, 4)
// -snip-
(游乐场)
那么这里一切都很好,每个条目都用相同的地址打印了 2 次:
1 (PrintAddr): 0xc0000ae030
3 (PrintAddr): 0xc0000ae060
2 (PrintAddr): 0xc0000ae048
2 (PrintAddr): 0xc0000ae048
3 (PrintAddr): 0xc0000ae060
1 (PrintAddr): 0xc0000ae030
0 (PrintAddr): 0xc0000ae018
0 (PrintAddr): 0xc0000ae018
但是为什么文章中的情况不适用于这里,而我没有得到很多3 (PrintAddr)
呢?