構造体とインターフェース
Go Pointers: & and *
Share a value instead of copying it, so a function can change the original.
学べること
- & takes an address
- * follows a pointer
- nil pointers
Passing 21 to a function
double(number)
- gets a copy
- number stays 21
doubleInPlace(&number)
- gets the address
- number becomes 42
An address instead of a copy
Go copies values when it passes them to a function. A pointer holds the address of a value, so a function that receives a pointer can change the original.
double changes only its own copy, so number stays 21. &number gives the address, and *value reads or changes what is stored there. Go follows a pointer to a struct for you, so counter.Count works. A pointer that points to nothing is nil.
重要なポイント
- Go copies arguments by default.
- &number is the address of number.
- *pointer reads or changes the value there.
実行できる Go のサンプル
Go
main.go
package main
import "fmt"
func double(value int) {
value *= 2 // changes only the copy
}
func doubleInPlace(value *int) {
*value *= 2 // changes the original through the pointer
}
type Counter struct{ Count int }
func main() {
number := 21
double(number)
fmt.Println(number)
doubleInPlace(&number)
fmt.Println(number)
pointer := &number
*pointer = 7
fmt.Println(number, *pointer, pointer == &number)
counter := &Counter{}
counter.Count++ // Go follows the pointer for you
fmt.Println(counter.Count)
var missing *Counter
fmt.Println(missing == nil)
}
21
42
7 7 true
1
true練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
すべてのチャレンジ