Last active
August 29, 2015 14:16
-
-
Save giwa/a59e6ce51882b22dee46 to your computer and use it in GitHub Desktop.
Go by Example: Pointers ref: http://qiita.com/giwa@github/items/0b72dc6f6d90a7ce4022
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ go run pointers.go | |
initial: 1 | |
zeroval: 1 | |
zeroptr: 0 | |
pointer: 0x42131100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment