每次发生突变时都会出现新对象吗?

每次发生突变时都会出现新对象吗?

问题描述:

I have this go code

package main

import (
    "fmt"
)

type User struct {
    Name string
    Sex string
}

func main() {
    u := &User{Name: "Leto", Sex: "Male"}
    fmt.Printf("main() address: %p %p
", &u, &u.Name)
    Modify(u)
    Modify(u)
    Modify2(u)
    Modify2(u)
}

func Modify(u *User) {
    u.Name = "Paul11"
    fmt.Printf("Modify() address: %p %p
", &u, &u.Name)
}

func Modify2(u *User) {
    u.Name = "Leto"
    fmt.Printf("Modify() address: %p %p
", &u, &u.Name)
}

The output is

main() address: 0x1040a120 0x10434120
Modify() address: 0x1040a130 0x10434120
Modify() address: 0x1040a138 0x10434120
Modify() address: 0x1040a140 0x10434120
Modify() address: 0x1040a148 0x10434120

I wonder 1. why the address of the object after mutation is different. 2. why the first takes 16 bytes, and afterwards it is only 8 bytes. 3. why the mutated field is still using the same memory address.

Thanks!

The methods are printing the address of the receiver argument u, a **User.

Print u instead of &u and you will observe that the address remains the same. A new User value is not created on every mutation.

func Modify(u *User) {
  u.Name = "Paul11"
  fmt.Printf("Modify() address: %p %p
", u, &u.Name)
}

func Modify2(u *User) {
   u.Name = "Leto"
   fmt.Printf("Modify() address: %p %p
", u, &u.Name)
}

playground example