Chapter 3. Variables

Up until now, we have only seen programs that use literal values (numbers, strings, etc.), but such programs aren’t particularly useful. To make truly useful programs, we need to discuss two new concepts: variables and control flow statements. This chapter will explore variables in more detail (we’ll discuss control flow statements in Chapter 4).

A variable is a storage location, with a specific type and an associated name. Let’s change the program we wrote in Chapter 1 so that it uses a variable:

package main

import "fmt"

func main() {
    var x string = "Hello, World"
    fmt.Println(x)
}

Notice that the string literal from the original program still appears in this program, but rather than send it directly to the Println function, we assign it to a variable instead. Variables in Go are created by first using the var keyword, then specifying the variable name (x) and the type (string), and finally, assigning a value to the variable (Hello, World). Assigning a value is optional, so we could use two statements, like this:

package main

import "fmt"

func main() {
    var x string
    x = "Hello, World"
    fmt.Println(x)
}

Variables in Go are similar to variables in algebra, but there are some subtle differences. First, when we see the = symbol, we have a tendency to read that as “x equals the string Hello, World.” There’s nothing wrong with reading our program that way, but it’s better to read it as “x takes the string Hello, World” or “x is assigned the string Hello, World.” ...

Get Introducing Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.