Learning GO! | Variables and Constants in GO | By Anjal Bam

Search for a command to run...

In this series, we will learn Golang beginners. And explore the world of GO inside out.
Why Go, and what can it do?
Let's get started with the developers' nightmare, Software Testing. The term "testing" in software development refers to the process of verifying and validating if the software is bug-free and meets the requirements specifications as guided by its de...

Why Go, and what can it do?

Dockerize Django and React applications the easy way.

Encrypt and decrypt like a pro.

In my previous tutorial, What the heck is GO!! we covered what Go or Golang is, installation and basic hello world in Go.
This tutorial mainly focuses on Variables and Constants in GO.
A Variable is a container that stores some data. Simple as that. Since Go is a statically typed programming language, the type of a variable is to be set on declaration and is not changed throughout the execution.
The variable declaration syntax in GO is:
var identifierName type
Example
var name string
var age int
var isProgrammer bool
NOTE: When a value is defined like shown above, the variable is automatically assigned a zero-value defined for the specific data-type. A datatype is consists of a set of values and operations that can be carried out on the data.
We can declare a variable and initialize it on the same line if we know the value it holds beforehand. The syntax:
var myName string = "Anjal"
var myAge int = "22"
This means the variable will infer the type of the variable from the data we provided.
var myName = "anjal"
var keywordvariable_name := value
myName := "Anjal" // The variable myName is of type string
Multiple variables can also be declared in a same line as:
var firstName, lastName string = "Anjal", "Bam"
birthMonth, birthDay := 12, 01
The variables in Go can be grouped together in a block for better readability and better code quality.
var (
name = "Anjal"
age = 22
lovesGo = true
)
Note: If the values are not initialized to the declared value, Go will automatically set it to the default value known as the zero-value of the type.
The constants are the identifiers with a fixed value that may not be changed.
package main
import "fmt"
const NAME string = "Anjal"
const AGE = 22
func main() {
fmt.Println(NAME)
fmt.Println(AGE)
}
const (
PRODUCT = "Shoes"
QUANTITY = 1
PRICE = 110.25
STOCK = true
)
NOTE: The variables are all uppercase by convention (Although not necessary).
These are the following rules for naming a Golang variable:
Concluding this post, we covered the variables and constants with different ways we can use to declare these variables.