0
0

More than 1 year has passed since last update.

[Go] Structの子要素を親要素のポインタで変更できるのか

Posted at

はじめに

Structのポインタを渡して中身を変更するときに子要素のStructの中身も変更できるのか分からなかったので検証しました。

バージョン:Go 1.16

検証

package main

import "fmt"

type Child struct {
    AAA string
}

type Parent struct {
    BBB   string
    Child Child
}

func changeParent(p *Parent) {
    p.BBB = "ccc"
}

func changeChild(p *Parent) {
    p.Child.AAA = "ddd"
}

func changeChildDirect(c *Child) {
    c.AAA = "eee"
}

func main() {
    c := Child{
        AAA: "aaa",
    }

    p := Parent{
        BBB:   "bbb",
        Child: c,
    }

    fmt.Println(p)
    // {bbb {aaa}}

    changeParent(&p)

    fmt.Println(p)
    // {ccc {aaa}}
    // これは当然変わる

    changeChild(&p)

    fmt.Println(p)
    // {ccc {ddd}}
    // 子要素もちゃんと変わった

    changeChildDirect(&c)

    fmt.Println(p)
    // {ccc {ddd}}
    // オブジェクトを渡した時点で中身がコピーされるのか、元の子要素を変えてもここは変わらない。
}

結論

親要素のポインタで子要素のStructの中身も変わる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0