Variables in Golang

Variables are used to store data in the program. A variable represents a named section in memory that can store some value. To define a variable, use the var keyword, followed by the name of the variable, followed by its type:

var variable_name

The variable name represents an arbitrary identifier that consists of alphabetic and numeric characters, and an underscore. In this case, the first character must be either an alphabetic character or an underscore.

Simplest Definition

For example, the simplest definition of a variable is:

var name string

This variable is called name and it represents the string type, i.e. some string.

You can declare several variables separated by commas at the same time:

var name,title,description string

In this case, variables name, title, and description are defined, which are of type string. In this case, again, the data type is specified at the end, and all variables belong to that type.

Assigning Value to a Variable

After defining a variable, you can assign it a value that corresponds to its type:

package main
import "fmt"
func main() {
    var name string
    name = "techieclues"
    fmt.Println(name)
}

Because the name variable is of type string, you can assign a string to it. In this case, the name variable stores the string "techieclues". Using the Println function, the value of this variable is printed to the console.

Case-Sensitive

It's also important to keep in mind that Go is a case-sensitive language, meaning variables named "name" and "Name" will represent different variables:

package main
import "fmt"
func main() {
    var name string
    name = "techieclues"
    fmt.Println(Name)
}

We should get an error here because the variable "Name" is not defined:

You can also assign an initial value to a variable right away when you declare it. This technique is called initialization:

var name string = "techieclues"

Define Several Variables

If we want to define several variables at once and assign initial values to them, we can wrap them in parentheses:

var (
    name string = "Docker"
    title string = "learn Docker"
)

A brief definition of a variable in the following format is also acceptable:

var name:=  "Docker"

In this case, the data type is not explicitly specified, it is automatically derived from the assigned value.