Go Variables

Walden Systems Geeks Corner tutorial Go Variables Rutherford NJ New Jersey NYC New York City North Bergen County

A variable is a name given to a storage area that the programs can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the operations that can be applied to the variable. The name of a variable can contain letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Go is case-sensitive.

A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type. There are two types of variable declarations, explicitly typed variables and implicitly typed variables. Below is an example of an explicitly typed variable

package main

import "fmt"

func main() {

    var a, A, b int;
    a = 10 ;
    A = 15 ;
    b = 20 ;

    fmt.Println(a)
    fmt.Printf("a is of type %T", a)
    fmt.Println(A)
    fmt.Printf("A is of type %T", A)
    fmt.Println(b)
    fmt.Printf("b is of type %T", b)
}


Variables can be initialized in their declaration. The type of variable is automatically judged by the compiler based on the value passed to it. The initializer consists of an equal sign followed by a constant expression. In the example below, the variables a and b are int.

package main

import "fmt"

func main() {

    var a int = 5
    fmt.Println(a)
    fmt.Printf("y is of type %T", a)
}

Implicitly typed variables

An implicitly typed variable declaration requires the compiler to interpret the type of the variable based on the value passed to it. The compiler does not require a variable to have type statically as a necessary requirement. Dynamic type variables are declared with the :=. In the example below, y is type int.

package main

import "fmt"

func main() {

    y := 10
    fmt.Println(y)
    fmt.Printf("y is of type %T", y)
}