Variables and Types

Give your data a name with var and :=

8 min read

A variable is a named box that holds a value. Instead of repeating the number 42 all over your program, you store it once under a name and use the name. Names make code readable, and letting values change over time is what makes programs powerful.

Declaring with var

var age int = 12
var name string = "Ada"

Read the first line as: create a variable called age, whose type is int (a whole number), starting at 12. Every variable in Go has exactly one type, and it keeps that type for life. A box made for numbers can never hold text.

Letting Go figure out the type

If you give a starting value, Go can see the type for itself, so you may leave it out:

var age = 12
var name = "Ada"

Go looks at 12 and says: that is an int. It looks at "Ada" and says: that is a string. This is called type inference, and it keeps code short without losing safety.

The famous := shortcut

Inside a function, Go offers an even shorter form that declares and assigns in one step:

func main() {
    age := 12
    name := "Ada"
    fmt.Println(name, "is", age)
}

:= means create this variable and give it this value. It is the most common way Go programmers declare variables, and you will use it constantly. Two rules to remember:

  • := only works inside functions. At the top of a file, use var.
  • := creates a new variable. To change one that already exists, use plain =.
score := 10
score = 15

The first line creates score. The second updates it. Writing score := 15 again in the same place would be an error, because the variable already exists.

Zero values

If you declare a variable without a starting value, Go fills the box with a sensible default called the zero value:

  • int starts at 0
  • string starts as "", the empty string
  • bool (true or false) starts as false

Go refuses to compile a program with a variable you declared but never used. Like the unused import rule, this keeps your code honest: everything present is there for a reason.

Quick check

Q1 What does score := 10 do?

Q2 Where is the := shortcut allowed?

Want to save your progress? It's free.

Create a free account