0 votes
in GoLang by
What are the Variables in Golang

1 Answer

0 votes
by

Variables point to a memory location which stores some kind of value. The type parameter(in the below syntax) represents the type of value that can be stored in the memory location.

Variable can be declared using the syntax

    var <variable_name> <type>

Once You declare a variable of a type You can assign the variable to any value of that type.

You can also give an initial value to a variable during the declaration itself using

    var <variable_name> <type> = <value>

If You declare the variable with an initial value, Go an infer the type of the variable from the type of value assigned. So You can omit the type during the declaration using the syntax

    var <variable_name> = <value>

Also, You can declare multiple variables with the syntax

    var <variable_name1>, <variable_name2>  = <value1>, <value2>

The below program in this Go tutorial has some Golang examples of variable declarations

 
package main
import "fmt"

func main() {
    //declaring a integer variable x
    var x int
    x=3 //assigning x the value 3 
    fmt.Println("x:", x) //prints 3
    
    //declaring a integer variable y with value 20 in a single statement and prints it
    var y int=20
    fmt.Println("y:", y)
    
    //declaring a variable z with value 50 and prints it
    //Here type int is not explicitly mentioned 
    var z=50
    fmt.Println("z:", z)
    
    //Multiple variables are assigned in single line- i with an integer and j with a string
    var i, j = 100,"hello"
    fmt.Println("i and j:", i,j)
}

The output will be

x: 3
y: 20
z: 50
i and j: 100 hello
...