How to Declare a Variable with := (Short Variable Declaration) in Go
Inside a Go function, name := "Ada" declares a variable and gives it a value in one step, with the type worked out from the value. Later changes use a plain =. Most Go code declares its local variables this way.
Syntax
<name> := <value>
<name> = <new value>
| Part | What it does |
|---|---|
:= | Declares a new variable and assigns its first value. Only inside functions. |
= | Assigns a new value to a variable that already exists. |
| Type | Taken from the value, and fixed from then on. |
The Go specification calls it "shorthand for a regular variable declaration with initializer expressions but no types", and adds that, unlike regular declarations, it "may redeclare variables provided they were originally declared earlier in the same block … and at least one of the non-blank variables is new."
The Example
The example declares a name and a year with :=, changes the name with =, and prints both.
Prerequisites
- Go.
go runcompiles and runs a single file. This guide uses Go 1.27.4.
Step 1: Write the Code
Create a file named main.go:

package main
import "fmt"
func main() {
name := "Ada"
year := 1815
name = "Grace"
fmt.Println(name, year)
}
Step 2: Run It
go run main.go
Grace 1815

The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Using := outside a function | syntax error: non-declaration statement outside function body | Use var x = 1 at package level |
Using := again for the same variable, as in a := 1 then a := 2 | no new variables on left side of := | Use = to change it |
| Declaring a variable and never using it | declared and not used: x | Use it, or remove it |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
no new variables on left side of := | Every variable on the left already exists | Switch to = |
declared and not used | A variable is assigned but never read | Use it or delete it |
FAQ
When should I use var instead?
Outside functions, where := isn't allowed, and when you want a variable that starts at its zero value, as in var count int.
Can := declare several variables at once?
Yes: quotient, remainder := divide(17, 5) declares both from a function's two results.
Conclusion
name := value declares a local variable and sets it in one step, with the type taken from the value; = changes it later. Use var at package level.
Additional Resources
- Short variable declarations, in the Go specification.
- A Tour of Go: Short variable declarations.
