2
2

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 5 years have passed since last update.

Go by Example: Pointers

2
Last updated at Posted at 2015-03-06

(この記事は Go by Example: Pointers を翻訳したものです。)

Goは、pointersをサポートしています。プログラムのの中で値とで構造体への参照を渡すことができます。

package main

import "fmt"

// zeroval, zeroptrの2つの関数を値と比較してポインタがどのように動くかを見ていきます。zerovalはintのパラメータを持っています。引数が渡される事によってパラメータに代入されます。zerovalは呼ばれた関数の中の変数とは違うivalのコピーを得ます。
func zeroval(ival int) {
    ival = 0
}

// zeroptrは対照的に*intがパラメータです。これは、intのポインタをパラメータとして取ることを意味します。関数のbody中の*iptr参照先の値をメモリアドレスを参照しそのアドレスの現在の値を取得します。ポインターを参照して代入される値は参照された値を変更します。
func zeroptr(iptr *int) {
    *iptr = 0
}

func main() {
    i := 1
    fmt.Println("initial:", i)
    zeroval(i)
    fmt.Println("zeroval:", i)

	// &i 文法はiのメモリのアドレスを返します。たとえば,下記の例はiへのポインタです。
    zeroptr(&i)
    fmt.Println("zeroptr:", i)

	// ポインタはプリントすることもできます。
    fmt.Println("pointer:", &i)
}
$ go run pointers.go
initial: 1
zeroval: 1
zeroptr: 0
pointer: 0x42131100
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?