Variables in GoLang

Variables are essential to any programming language. Now, we will see how you can use variables in GoLang. Since Go is a statically typed programming language, that means the variable type is inferred before compilation.

The “var” keyword

The var keyword is used to declare a variable. The code below shows how the variable declaration is done in Go.

package main

import "fmt"

func main() {
        var name = "John Doe"           // no type declaration
        var username string = "John123" // type declaration
        var numberOfPosts int           // no initialization
        fmt.Println(numberOfPosts)      // prints 0

In the code above name is declared and then initialized with the var keyword but not its type. Since a string is used to initialize, the variable name is a string. Go infers the type from the initialization.

Initialization shorthand syntax

Initialization shorthand enables us to initialize variables in a concise manner. Which means we can initialize without using var and declaring datatype of that variable. Let’s see how to use that syntax.

package main

import "fmt"

func main() {
        name := "Jane Doe"  // notice the colon equal syntax

In the code above the syntax should be noticed. The new addition is the := operator. We no longer need the var keyword and type specifier.

Datatypes in Go Language

There are many data types in Go. Int, float, string, booleans and other derived types are also there. Below are the supported ones.

Integer: Int8, int16, int32, int64, uint8, uint16, uint32, uint64

Float: float32, float64, complex64, complex128 (Go supports complex numbers as well!)

Numeric types like byte (uint8), rune (int32), uint (32/64), int, uintptr.

Strings are there. And there are derived types mentioned below.

Pointers, Arrays, Structures, Unions, Functions, Slices, Interfaces, Maps and Channels are all derived types.

There are so many different data types for our specific needs. This makes writing Go code flawless. The static typing saves a lot of debugging work as well.

As you can see, declaring and using variables in Go is really easy.