Go: Define Variables

Go: Define Variables

Learn how to define variables in Go

Β·

2 min read

In Go we can declare variables using the keyword var. The variables can be visible in global scope or local. Global variables are defined at the 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 parenthesis. So you define a bloc of variables, separated by a 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. We will explain type inference in a future article.


Fundamentals

Go is a statically typed language, which means variables must be declared before use and have a specific type. Go has support for basic types like string, int, float, bool, etc. Go also has composite types like arrays, slices and maps.

  • Variables in Go are lexically scoped - either function-scoped or package-scoped.

  • Variables declared inside a function are only accessible within that function.

Go does not have global variables in the traditional sense. Variables declared outside all functions are package scoped and can be accessed by any function in that package.

Go does not have public or private variables. All variables are accessible to any code within the same package.

Variables in Go are statically typed. Once a variable is declared to be of a specific type, it cannot be given a value of a different type. The compiler will catch type mismatches.


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

Β