1
0

More than 1 year has passed since last update.

goのポインタ

Last updated at Posted at 2022-04-17

ポインタ

  • ポインタを渡すというのは、変数の内容を渡すのではなく、変数のメモリの値を渡すという意味
    • なので、渡された関数などで、値の変更が合った場合は、渡された関数の外であってもそのポインタを参照すると値は変わっている
  • ポインタではない通常の変数のわたし方の場合は、変数のコピーが渡されるため、関数内で値が変わった場合、変数が渡された関数の中と外でその変数を参照しても値は変わっている
package main

import "fmt"

// ポインタ
func pointer(x *int) {
	*x += 1
	fmt.Println("ponter func: ", *x)
}

// ポインタではない
func nopointer(x int) {
	x += 1
	fmt.Println("nopointer func: ", x)
}

func main() {
	z := 2
	pointer(&z)
	fmt.Println(z)

	fmt.Println("------------")
	y := 2
	nopointer(y)
	fmt.Println(y)
}

出力

 yuta  ~  gotest  go run main.go
ponter func:  3
3
------------
nopointer func:  3
2
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