Showing posts with label Variables. Show all posts
Showing posts with label Variables. Show all posts

Monday, November 23, 2020

Zero Values in Go

Would you be able to define what is a Zero Value in Go?

On a previous article we discussed all about variables. However, declaring variables is just one piece of the equation. Since go does not have nulls, would you be able to tell what value  each primitive type is assigned?

If you though zero values then you're right. But would you be able to tell how to declare and use them 

On this article let's continue our discussion on variable initialization in Go discussing Zero Values.

Zero Values

One important difference between Go and other programming languages is that in Go, a variable cannot be null (or undefined). In Go, variables declared and not initialized will have a default value associated to them also known as Zero Value.

Zero values are an important concept of Go and worth understanding well regardless of your programming skills. One of the big advantages they provide is that, by not having nulls, your code will not be subject to Null Pointer Exceptions, one of the biggest reason for bugs, crashes and security issues in other programming languages.

How to set Zero Values?

But how do we set variables to their zero values? If you read our previous tutorial you know that every variable non-initialized by default set its zero value.

Confusing? Better learn from an example then.

On the program below, none of variables was initialized thus, set to their respective zero value. Would you be able to tell what's this program outputs?

package main

import "fmt"

func main() {
var i int
var f float64
var b bool
var s string
var arr [3]string     // an array[3] of strings
fmt.Printf("%v %v %v %v %v\n", i, f, b, s, arr)
}

If you guessed 0 0 false "" [ ] congratulations! So let's see which are the zero values for the most common types.

Zero Values for Common Types

The zero values for the most common types:

  • int, float64 (and other numeric types): 0
  • bool: false
  • string: "" (empty string)
  • arrays/slices: [ ] (empty, not null/nil)
  • custom types: {} (we'll learn about them later)

When to use Zero Values?

The last topic to cover about zero values is when to use them? Well, if you have experience in other programming languages you understand that you don't always have the value you need at hand. For all these use cases, you should declare your variables without initializing them. For example:

var b bool

Conclusion

On this article we learned about Zero Values in Go. Zero Values are an important concept in Go that's worth understanding as they're widely used in Go programs and libraries. Learning and using Zero Values is important to make your code more robust and readable.

See Also

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