Follow

Follow
Go: Define Variables

Go: Define Variables

Elucian Moise's photo
Elucian Moise
Β·Mar 22, 2023Β·

1 min read

In Go we can declare variables using keyword var. The variables can be visible in global scope or local. Global variables are definet at package level. Local variables can be defined in functions.

Example:

package main

import "fmt"

// global variables
var i, j int = 1, 2

func main() {
    // local variables
    var (
        c = true
        p = false
        g = "no"
    )
    // verify values
    fmt.Println(i, j, c, p, g)
}

Try it: https://go.dev/play/p/dpNPeXsHLMR

Note:


You can factor out keyword var using paranthesis. So you define a bloc of variables, separated by new line. Can you see each variable has a different type? The type is not specified because Go can use type inference to assign default type to variables.

Type inference is based on data literals. Specific data literals will create specific data types. Once the type is established it can't be changed.


Enjoy life. Learn and prosper πŸ––πŸΌπŸ€

Β 
Share this