Monday, November 16, 2020

Variables in Go

Understand all about declaring and using variables in Go

Once you understand the main reasons to use Go, installed Go on your Windows, Linux or Mac, and built your first program in Go, it's time to dive into the details of the language. While most developers are familiar to these concepts, Go approaches that in different ways that are worth exploring.

Built-in types

Variables are essential to any programming language. In Go, the built-in types are boolean, integer, float and string. The language also offers support for arrays, maps and declaring our custom types which we'll see in a future article.

Another aspect that's worth mentioning is that Go is a statically typed programming language, meaning that the variable type is inferred before compilation.

On this post we well study:

  1. the basics of variables in Go
  2. declaring variables with the "var" keyworkd
  3. declaring variables using the shorthand syntax
  4. zero values

The basics of variables in Go

So let's start with the basics of variables in Go. Essentially:

  • there are two ways to initialize variables
  • it's possible to declare and initialize multiple variables (and values) at the same time
  • there are no null variables in Go
  • Every value has a default value (also called Zero Value)
  • you can access/pass values via pointers
  • the compiler does not allow unused variables
Let's discuss them.

Declaring variables using the “var” keyword

The first way to initialize variables in Go is by using the var keyword. For example:

package main

import "fmt"

func main() {
     var name = "John Smith"                 // Snippet 1
     var email string = "john@smith.com"     // Snippet 2
     var address string                      // Snippet 3
     var age int                             // Snippet 4
     fmt.Println(name, email, address, age)  // Snippet 5                           
}

Where, on:

  1. Snippet 1: we declared a variable assigned a value to it. Go infers the type from the initialization automatically for us
  2. Snippet 2: similar to snippet 1 but specifying our type. Note: this use is not recommended as its unnecessarily verbose. In Go, we prefer simplicity
  3. Snippet 3: we declared a variable of type string but didn't assign any value to it. Go will set its zero value which is "" (empty).
  4. Snippet 4: we declared a variable of type int but didn't assign any value to it. Go will set its zero value which is 0.
  5. Snippet 5: we print our variables. This program will not build if we don't use the variables we declare.

Declaring variables using the shorthand syntax

While the above makes sense if you know the value of the variable you could initialize it more concisely with the following syntax:

package main

import "fmt"

func main() {
   name := "John Smith"
   age := 32
   fmt.Println(name, age)
}

On both examples we declared a variable and assigned a value to it. Go infers the type from the initialization automatically for us (string and int on this case).

However there are two things to notice about this syntax. First, the := operator cannot be used to reasign a value to an already declared variable. Think of its purpose as declare and set. So, if you tried to update the name var to something else, you'd get this error:

no new variables on left side of :=

Another thing to note is that the shorthand syntax for declaring a variable does not work outside of a function. For example, the example below:

package main
import "fmt"

name := "John Smith"

func main() {
    age := 32
    fmt.Println(name, age)
}

Would fail with:

syntax error: non-declaration statement outside function body

To properly initialize it, we should have used the var keyword as in:

package main
import "fmt"

var name = "John Smith"

func main() {
    age := 32
    fmt.Println(name, age)
}

Declaring multiple variables at the same time

Go also allows you to declare (and set values for) multiple variables at the same time using the abbreviated syntax:

package main
import "fmt"

func main() {
    name, id:= "John Smith", 123456           // Snippet 1
    fmt.Println(name, id)
}

Or, by wrapping them around the var keyword:

package main
import "fmt"

func main() {
    var (
       a int
       b = 1
       c int = 2
       d, e = 3, "test"
       f, g string
     )
    fmt.Printf("%v %v %v %v %v %v %v\n", a, b, c, d, e, f, g)
}

Note that the above syntax only works if you if you provide values for all variables. 

name, email := "John" // error: no value specified for email

Unused Variables

It's important to note that every variable declared in Go must be used. You will get a compile-time error if your code has an unused variable. And that's a good thing since it makes the code cleaner and less error-prone.

The special identifier _

Go also offers the special identifier _ which can be assigned values. It works as a black hole meaning that values assigned to it will be ignored and will save you from declaring (and reading) a variable you don't need too. We'll cover more about this special variable in future posts.

Naming Variables

Variables in Go are usually declared using the "camel case" syntax. Go also does not impose any restrictions on the size but usually smaller is preferred. And as in most languages, variables can be named using standard ascii characters with the difference that Go also accepts any Unicode character considered a letter or digit. For example, the below code would work:

π := 3.14159
fmt.Println("The value of pi is", π)

The value of pi is 3.14159

However, we recommend keeping it simple and only using ASCII chars for your variables:

name := "John"
age := 22
fmt.Printf("%v is %v years old", name, age)

Tuple Assignments

Keep in mind the difference between := and =. The first is a declaration while the second is an assignment. In Go, we saw that we can do multiple assignments at the same time:

i, j = j, i // swap values of i and j

Zero Values

Another important concept in Go is Zero Values. While we will study them later, for now, we want you to understand that in Go, no variable will ever be null. Variables declared and not initialized will have a default value associated to them (aka, zero value).

Zero values are an important concept of Go and worth understanding well if you come from other programming languages. For more information, check this article.

Conclusion

On this post we studied different ways to declare and initialize our variables. We also discussed some errors that may occur and provided recommendations on how to use them. We hope it helps!

See Also

Any comment about this page? Please contact us on Twitter

Featured Article

Pointers in Go

Understand all about declaring and using pointers in Go If you're coming from Python, Java, JavaScript, C# and others, tal...

Popular Posts