KDOC 653: var と := の違い
この文書のステータス
- 作成
- 2026-10-11 貴島
- レビュー
- 2026-10-11 貴島
概要
Go で当たり前に使っている var x = 1 と x := 1 の違いが気になった。微妙な違いがある。
It is shorthand for a regular variable declaration with initializer expressions but no types:
“var” IdentifierList “=” ExpressionList .
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
Short variable declarations may appear only inside functions. In some contexts such as the initializers for “if”, “for”, or “switch” statements, they can be used to declare local temporary variables.
訳
これは、初期化式を含むが型指定のない通常の変数宣言の省略形です:
“var” IdentifierList “=” ExpressionList .
通常の変数宣言とは異なり、短縮変数宣言では、同じブロック内(ブロックが関数本体である場合はパラメータリスト内)で以前に同じ型で宣言されており、かつ空白以外の変数のうち少なくとも1つが新規である場合に限り、変数を再宣言することができます。その結果、再宣言は多変数短縮宣言でのみ使用できます。再宣言によって新しい変数が導入されるわけではなく、元の変数に新しい値が代入されるだけです。
短縮変数宣言は関数内部でのみ使用できます。「if」、「for」、または「switch」文の初期化子など、一部の文脈では、ローカルの一時変数を宣言するために使用できます。
The Go Programming Language Specification - Short variable declarations
関連
なし。