LoginSignup
2
2

More than 5 years have passed since last update.

GOのポインタ

Last updated at Posted at 2018-05-19

Goはポインタを扱います。 ポインタは値のメモリアドレスを指します。

変数 T のポインタは、 *T 型で、ゼロ値は nil です。

var p *int

& オペレータは、そのオペランド( operand )へのポインタを引き出します。

i := 42
p = &i  // i のポインタを代入する

* オペレータは、ポインタの指す先の変数を示します。

fmt.Println(*p) // ポインタ p を通して i から値を読みだす
*p = 21         // ポインタ p を通して i へ値を代入する

これは "dereferencing" または "indirecting" としてよく知られています。

なお、C言語とは異なり、ポインタ演算はありません。

i, j := 42, 2701

p := &i         // i のポインタを p に代入する
fmt.Println(*p) // 「42」 ポインタ p を通して i から値を読みだす
*p = 21         // ポインタ p を通して i へ値を代入する
fmt.Println(i)  // 「21」 i の値は新しい値へ変わる

p = &j         // j のポインタを p に代入する
*p = *p / 37   // ポインタ p を通して j の値を演算する
fmt.Println(j) // 「73」 演算された j の値が表示される

参考

A Tour of Go / Pointers

2
2
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
2
2