package main import "fmt" type Test struct { value int } func One(test *Test) { test.value = 1 fmt.Println("one") } func execute() Test { x := Test{0} defer One(&x) // xのポインタをOne関数に渡して、0を1に更新 return x } func main() { x := Test{0} One(&x) fmt.Println(x) y := execute() fmt.Println(y) // このyがOne関数によって更新された値にならず、0が出力されるのは何故だろう }
関数が値を返すときに、関数の中で生成した値と実際に返した値のアドレスが別になる(=コピーが返される)のではと思った。
package main type Test struct { value int } func One(test *Test) { test.value = 1 } func execute() Test { x := Test{0} defer One(&x) print(&x) return x } func main() { y := execute() // ここで出力されるアドレスと print("\n") print(&y) // ここで出力されるアドレスは異なる }
そういうことらしい。 メソッドチェーンでsetter呼びまくったりするとどんどん初期化されてコストかかりそう? こういうの体系的に学べるチュートリアルかなんかないかな。
package main import "fmt" type Test struct { value int } func One(test *Test) { test.value = 1 fmt.Println("one") } func execute() *Test { x := Test{0} defer One(&x) // xのポインタをOne関数に渡して、0を1に更新 return &x // コピーではなくそのまま返したければポインタで返す } func main() { y := execute() fmt.Println(*y) }
コピーではなくそのまま返したければポインタで戻せばいいのか。