Goでポインタが指す構造体をコピーしたい時

よく忘れるのでメモ。入れ物作って値代入でいける。

fuga := &A{}
*fuga = *hoge

Go Playground

package main

import (
    "fmt"
)

type A struct {
    X int
    Y string
    Z []float64
}

func main() {
    var (
        hoge *A
        fuga *A
    )

    hoge = &A{
        X: 1,
        Y: "test",
        Z: []float64{0, 1, 2, 3, 4},
    }

    fuga = &A{}
    *fuga = *hoge

    hoge.X = 3
    hoge.Y = "TEST"
    hoge.Z = []float64{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}

    fmt.Printf("%#v\n", hoge)
    fmt.Printf("%#v\n", fuga)
}
&main.A{X:3, Y:"TEST", Z:[]float64{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}}
&main.A{X:1, Y:"test", Z:[]float64{0, 1, 2, 3, 4}}

https://play.golang.org/p/0Ry9AnAAySP

Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.