Skip to main content

How to Declare a Variable with := (Short Variable Declaration) in Go

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<name> := <value>
<name> = <new value>
PartWhat it does
:=Declares a new variable and assigns its first value. Only inside functions.
=Assigns a new value to a variable that already exists.
TypeTaken 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 run compiles and runs a single file. This guide uses Go 1.27.4.

Step 1: Write the Code​

Create a file named main.go:

main.go, which declares name := "Ada" and year := 1815, assigns name = "Grace" and prints name and year.

main.go
package main

import "fmt"

func main() {
name := "Ada"
year := 1815

name = "Grace"
fmt.Println(name, year)
}

Step 2: Run It​

Terminal
go run main.go
Output
Grace 1815

A zsh terminal where go run main.go prints Grace 1815.

The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Using := outside a functionsyntax error: non-declaration statement outside function bodyUse var x = 1 at package level
Using := again for the same variable, as in a := 1 then a := 2no new variables on left side of :=Use = to change it
Declaring a variable and never using itdeclared and not used: xUse it, or remove it

Troubleshooting​

SymptomLikely causeFix
no new variables on left side of :=Every variable on the left already existsSwitch to =
declared and not usedA variable is assigned but never readUse 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​