How to Use := Operator in Go: Syntax and Examples
In Go, the
:= operator is used for short variable declaration and assignment in one step. It declares new variables and assigns values without needing the var keyword. This operator can only be used inside functions.Syntax
The := operator combines declaration and assignment in one step. It declares one or more new variables and assigns values to them.
variableName := value: declares and assigns a single variable.var1, var2 := val1, val2: declares and assigns multiple variables at once.- It can only be used inside functions, not at the package level.
go
x := 10 y, z := 20, "hello"
Example
This example shows how to use := to declare variables and print their values.
go
package main import "fmt" func main() { a := 5 b, c := 10, "Go" fmt.Println("a:", a) fmt.Println("b:", b) fmt.Println("c:", c) }
Output
a: 5
b: 10
c: Go
Common Pitfalls
Common mistakes when using := include:
- Trying to use
:=outside functions (package level) causes errors. - Using
:=when all variables are already declared causes an error; at least one variable must be new. - Confusing
=(assignment) with:=(declaration + assignment).
go
package main
func main() {
x := 1
// Wrong: redeclaring x without new variable
// x := 2 // Error: no new variables on left side
// Correct: redeclare x with a new variable y
x, y := 2, 3
}Quick Reference
| Usage | Description |
|---|---|
| x := 10 | Declare and assign variable x with 10 inside a function |
| a, b := 1, 2 | Declare and assign multiple variables a and b |
| x = 20 | Assign new value to already declared variable x |
| Outside function: x := 10 | Invalid: short declaration only allowed inside functions |
Key Takeaways
Use := to declare and assign new variables inside functions in one step.
At least one variable on the left side of := must be new.
:= cannot be used outside functions or for variables already declared without new ones.
Use = to assign values to variables already declared.
Short declaration makes code concise and readable inside functions.