go struct做爲值函數參數須要注意的地方

struct做爲值函數參數須要注意的地方,則是copy一份, 可是struct 裏面的指針則也是copy地址,
則改變原來結構中指針指向的數據, 將相應改變copy以後裏面的指針指向的值, 由於它們指向的是同一個地址. 函數

package main

import (
    "fmt"
)

type test struct {
    id   int32
    name string
}

type test2 struct {
    id int32
    t  *test
}

func main() {

    var t2 = test2{
        id: 1,
        t: &test{
            id:   2,
            name: "she",
        },
    }
    t3 := t2
    fmt.Println(t2.id, *t2.t)
    fmt.Println(t3.id, *t3.t)
    t3.t.id = 9
    fmt.Println(t2.id, *t2.t)
    fmt.Println(t3.id, *t3.t)

} spa

輸出: 指針

1 {2 she}
1 {2 she}
1 {9 she}
1 {9 she} string

須要注意指針問題. test

相關文章
相關標籤/搜索