2019-10-16 Golang copy struct

2019-10-17  本文已影响0人  Sea_Shore

The go is passing by value.
That is, if I do
a = b
a is a copy of b.

But if a and b are pointers.
if I do a = b.
it's pass by reference.
to copy value,
I need to do
*a = *b

package main

import (
    "fmt"
)

type T struct {
    Id int
    Name string
}

func main() {
    fmt.Println("Hello, playground")
    
    // var t T
    t := &T{}
    t.Id = 3
    t.Name = "what"
    
    fmt.Printf("%v \n", t)
    
    // var t2 T
    t2 := &T{}
    
    *t2 = *t
    fmt.Printf("%v \n", t2) 
    
    t.Id =4
    fmt.Printf("%v \n", t)
    fmt.Printf("%v \n", t2) 
}
上一篇 下一篇

猜你喜欢

热点阅读