3 Ways Of Assigning Variables in Go

3 Ways Of Assigning Variables in Go

Go has become a go-to programming language lately. It's a statically typed language, meaning, it performs type-checking at compile time. If I iron out the jargon, it simply means that the code is first compiled, like in C/C++ and then, it'll be ready for execution, unlike Python.

The beauty of statically typed languages is that they try to be idiomatic or verbose as much as possible while defining or assigning values. It could be annoying for experienced developers, but it's good for beginners to know how things work in the background.

A variable is a placeholder or a storage location, with a specific data type and an associated name.

The Idiomatic Way

package main

import "fmt"

func main(){

var greet string = "Hello Dev"

fmt.Println(greet)

}

Variables in Go are created by first using the var keyword, then specifying the variable name greet followed by the type string, as we see from the above code (line 4).

In variables, \= symbol doesn't mean is equal to, unlike in Algebra. The right way to read that is, “greet is assigned to the string Hello Dev” or “greet takes the string Hello Dev”.

As the name (variable) suggests, the variables can change their value throughout the lifecycle of a program.

package main

import "fmt"

func main(){

var greet string = "Hello Dev"

fmt.Println(greet)

greet = "Welcome Dev"

fmt.Println(greet)

}

If we execute the above code, we'll get the following result.

Code execution in Go

So the variable greet has been assigned to a new value Welcome Dev. Here's a caveat, we don't need to declare the var greet string again to reassign a different value. If we do so, we'll get an error message saying greet redeclared in this block.

Also remember, assigning a value at the start is optional, so we could use two statements as follows.

package main

import "fmt"

func main(){

var greet string 

greet = "Hello Dev"

fmt.Println(greet)

}

The Short Way

Instead of using var greet string or var greet string = "Hello Dev”, we can simply use greet := "Hello Dev”.

And there is no need to specify type because Go compiler will infer the type based on the literal value. For example, the words between quotes as “strings” and any number like 1 as int.

The Intuitive Way

Like greet := "Hello Dev”, we can also assign variables like var greet = "Hello Dev”. Hope these things make sense now.

As you become proficient in Go, it's more likely that you use := to assign values to a variable.

That's all for today, hope this post helped you to clear some doubts about variables in Go, if it did, I would like to know your opinion, please write down your views in the comments.