1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Go ポインタとは~なぜ必要?

Posted at

AWSのLambda関数を触っててGoのチュートリアルが読めなかったので、基礎的なところから勉強したことを記す。

#ポインタの概念
ポインタ=実体(インスタンス)が格納されたメモリのアドレス

package main

import "fmt"

func main() {

	var i int
    //int型の100という実体
	i = 100

    //int型のポインタ型変数pを定義
	var p *int
	p = &i

	fmt.Println(i) //100
	fmt.Println(p) //0xc00018c008
	fmt.Println(*p) //*をつけることでリテラル(数値や文字列を直接に記述した定数のこと)を参照できる
}

ここで疑問が湧いた。
ポインタってなぜ必要なのか?
それは、値渡しだけではなく参照渡しができるから。

値渡し

package main

import "fmt"

func main() {
	var i int
	i = 100

	fmt.Println(i) //100
	hoge(i)        //101
	fmt.Println(i) //100
}

func hoge(i int) {
	i += 1
	fmt.Println(i)
}

参照渡し

package main

import "fmt"

func main() {
	var i int
	i = 100
 
	fmt.Println(i) //100
	hoge(&i)       //101
	fmt.Println(i) //101
}

func hoge(i *int) {
	*i += 1
	fmt.Println(*i)
}


1
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?