Variable Declaration / Short Declaration
In Go, there are two ways to declare a variable: the var keyword and the short declaration operator :=. Knowing when to use each is important.
Syntax
// Declaration with var (explicit type) var variableName type var variableName type = value // Declaration with var (type inference) var variableName = value // Short declaration operator (only allowed inside functions) variableName := value // Declaring multiple variables at once var x, y int = 1, 2 a, b := 10, 20
Syntax Overview
| Syntax | Description |
|---|---|
| var name type | Declares a variable with an explicit type. The initial value is the zero value for that type. |
| var name type = value | Declares a variable with an explicit type and initial value. |
| var name = value | Declares a variable using type inference. The type is determined from the value on the right-hand side. |
| name := value | The short declaration operator. Only usable inside functions; declares and assigns a variable in one step using type inference. |
| var ( ... ) | A block syntax for declaring multiple variables together. Commonly used at the package level. |
Sample Code
package main
import "fmt"
// At the package level, use var (:= is not allowed here)
var appName string = "MyApp"
var version = 1.0 // type inference
func main() {
// Inside a function, both styles are available
var msg string = "Hello"
lang := "Go" // short declaration (most commonly used)
// Declaring multiple variables at once
var x, y int = 10, 20
a, b := 100, 200
fmt.Println(appName, version)
fmt.Println(msg, lang)
fmt.Println(x, y)
fmt.Println(a, b)
// var block
var (
name = "Tanaka"
age = 30
)
fmt.Println(name, age)
}
Notes
Inside functions, the short declaration := is the most concise form and is commonly used in Go code. At the package level (outside any function), only var can be used.
With type inference, Go automatically determines the type from the value on the right-hand side. For example, x := 42 produces an int, and x := 3.14 produces a float64. Use var when you want to specify the type explicitly or initialize a variable to its zero value.
:= must introduce at least one new variable on the left-hand side. Writing only already-declared variables on the left will cause a compile error. Also note that declaring a variable but never using it is itself a compile error in Go.
If you find any errors or copyright issues, please contact us.