Variables, Types and Keywords

In the next few sections we will look at the variables, basic types, keywords,and control structures of our new language.

Go is different from (most) other languages in that the type of a variable isspecified after the variable name. So not: int a, but a int. When youdeclare a variable it is assigned the “natural” null value for the type. Thismeans that after var a int, a has a value of 0. With var s string, s isassigned the zero string, which is "". Declaring and assigning in Go is a twostep process, but they may be combined. Compare the following pieces of codewhich have the same effect.

  1. var a int a := 15
  2. var b bool b := false
  3. a = 15
  4. b = false

On the left we use the var keyword to declare a variable and then assigna value to it. The code on the right uses := to do this in one step (this formmay only be used inside functions). In that case the variable type isdeduced from the value. A value of 15 indicates an int. A value of falsetells Go that the type should be bool. Multiple var declarations may alsobe grouped; const (see ) and import also allow this. Note theuse of parentheses instead of braces:

  1. var (
  2. x int
  3. b bool
  4. )

Multiple variables of the same type can also be declared on a single line: var x, y int makes x and y both int variables. You can also make use ofparallel assignment a, b := 20, 16.This makes a and b both integer variables and assigns20 to a and 16 to b.

A special name for a variable is . Any valueassigned to it is discarded (it’s similar to /dev/null on Unix). In thisexample we only assign the integer value of 35 to b and discard the value 34:, b := 34, 35. Declared but otherwise unused variables are a compiler errorin Go.