Go · Stage 1 – Storing Information · Lesson 8 of 64

Variables: Labeled Boxes

Store one value under a useful name and read it again later.

Inside the main function, create one variable and display it:

Go code

var name string = "Maya"
fmt.Println(name)
Line-by-line explanation
  1. var tells Go to create a variable.
  2. name is the label.
  3. string says the box stores text.
  4. = "Maya" places text in the box.
  5. Println reads and displays the stored value.
Expected output
Maya

Go displays the value, not the variable’s label.

A variable can receive a new value of the same type later:

Go code

name = "Noah"
fmt.Println(name)
Line-by-line explanation
  1. The variable already exists, so var is not repeated.
  2. The equals sign assigns a new string.
  3. Println displays the replacement value.
Expected output
Noah

The old value Maya has been replaced.