DEV Community

Runo-saduwa
Runo-saduwa

Posted on

Go variables: the bare minimum knowledge

Variables are one of the most important features of any programming language. It helps us to store data and also distribute data to various parts of our applications.

Here and now, we’ll learn what’s really necessary to learn about variables in Go.

First things first, The var keyword

Variables are declared in Go with the
var keyword. Easy peasy, let’s move on.

How to declare a variable

Let’s say we want to declare a variable called language which will hold a string value, how do we do that in Go?

Easy, we’ll simply write the var keyword followed by the variable name, which is language and finally the type of our variable, in this case it’s a string. See the code snippet below:

var language string

Go is a typed language so you should never omit specifying the type of the variable if it hasn’t yet been initialized with a value. We’ll talk about variable initialization in the next section.

How to initialize a variable

By now, we all know variables are like containers where we keep things, so what is variable initialization?

variable initialization is simply the process of assigning a value to a variable. So, in other words it’s like the process of putting things into a container.

Great, so how do we intialize a variable with a value in Go?

Looking back at our previous example above, let’s say we want to assign a value to the language variable. This can be accomplished by using the
= operator, see the example below!

import (
    "fmt"
)
var language string = English;

func main() {
    fmt.Println(language) //English 

}

When a variable is declared and explicitly initialized with a value, you can avoid specifying the type of the variable. The variable will take the type of the initializer, this is called inferred typing.

import (
    "fmt"
)
var language = English;

func main() {
    fmt.Println(language) //English

}

Implicit initialization

When a variable is declared without being initialized with a variable, it is implicitly initialized with a value according to the type of the variable.

  • If its a string type, it is initialized with ’’.
  • if it’s an interger int type, it’s initialized with 0.
  • if it’s a Boolean type it’s initialized with false.
import (
    "fmt"
)
var name string;
var age int;
var married bool;
func main() {
    fmt.Println(name, age, married) //‘’, 0, false

}

The short assignment statement

Inside a function you can initialize a variable with the short assignment statement := to save yourself time and to keep your code elegant and readable.

import (
    "fmt"
)

func main() {
   name := Runo;
    fmt.Println(name) //name

}

REMINDER: this can only be done inside a function and not in the package level.

Well, there you have it!, in my opinion this is the bare minimum knowledge one needs to work comfortably with Go variables.

Happy Coding!

Top comments (0)