Go の基礎
Go Variables and Constants: var, := and const
Two ways to declare a variable, what a zero value is, and values that never change.
学べること
- var and :=
- Zero values
- const
Declaration → result
var year int0, the zero valuescore := 10int, inferredconst MaxScore = 100cannot changeDeclare, then use
Go has two ways to create a variable. var names the type, and := lets Go work out the type from the value. A variable that is declared without a value gets a zero value such as 0 or an empty string.
year is declared without a value, so it starts at 0 until 2009 is assigned. := can only be used inside a function and can declare several variables at once. A const cannot be changed after it is declared.
重要なポイント
- var names the type; := infers it.
- A variable without a value starts at its zero value.
- A const cannot change.
実行できる Go のサンプル
Go
main.go
package main
import "fmt"
const MaxScore = 100
func main() {
var language string = "Go"
var year int // zero value: 0
score := 10 // short declaration, type inferred
score += 5
year = 2009
name, version := "gopher", 1.21
fmt.Println(language, year, score, MaxScore)
fmt.Println(name, version)
}
Go 2009 15 100
gopher 1.21練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
すべてのチャレンジ