LoginSignup
1
0

Goにおけるポインタ操作

Posted at

ポインタを学ぶ

3日目はポインタについてです。
Go言語においてポインタは非常に重要な概念です。

package main

import "fmt"

func main() {
	i, j := 42, 2701

	p := &i         // point to i
    fmt.Println(p)  // 0x1400009c018
	fmt.Println(*p) // read i through the pointer
	*p = 21         // set i through the pointer
	fmt.Println(i)  // see the new value of i

	p = &j         // point to j
	*p = *p / 37   // divide j through the pointer
	fmt.Println(j) // see the new value of j
}

実行する前に挙動を考えてみることにします。

変数pに変数iの番地を代入しています。

p := &i

pを直接出力するとメモリアドレスが入っていることがわかります。pはポインタ変数と呼びます。

次にポインタ変数のアドレスに格納されている値を参照するために、変数の前に*を付けて呼び出します。

fmt.Println(*p)

変数pには変数iのアドレスが格納されています。つまり、ここでは変数の値42が出力されます。

*p = 21

変数iの値を再代入しています。
直後では

fmt.Println(i)

21が出力されます。

p = &j
*p = *p / 37
fmt.Println(j) 

変数pに変数jのアドレスを代入し、変数pのアドレスの値である2701を37で除算し、変数jの値として再代入しています。
よって変数jの値は2701/37=73となります。

最期にプログラムを実行して確認してみましょう。

$ go run app/day3/main.go
0x1400000e0b8
42
21
73

よさそうです。

1
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
1
0