YouTip LogoYouTip

Go Variables

Go Variables

Variables originate from mathematics and are an abstract concept in computer languages that can store calculation results or represent values.

Variables can be accessed via their variable names.

Go variable names consist of letters, digits, and underscores, where the first character cannot be a digit.

The general form for declaring a variable uses the var keyword:

var identifier type

Multiple variables can be declared at once:

var identifier1, identifier2 type

Examples

package main

import "fmt"

func main() {
    var a string = ""
    fmt.Println(a)

    var b, c int = 1, 2
    fmt.Println(b, c)
}

The output of the above example is:


1 2

Variable Declaration

First method: specify the variable type. If not initialized, the variable defaults to its zero value.

var v_name v_type
v_name = value

The zero value is the value the system assigns by default when a variable is not initialized.

Examples

package main

import "fmt"

func main() {
    // Declare a variable and initialize it
    var a = ""
    fmt.Println(a)

    // No initialization, so it's the zero value
    var b int
    fmt.Println(b)

    // Bool zero value is false
    var c bool
    fmt.Println(c)
}

The output of the above example is:


0
false
  • Numeric types (including complex64/128) are 0
  • Boolean type is false
  • String is "" (empty string)
  • The following types are nil:
var a *int
var a []int
var a map int
var a chan int
var a func(string) int
var a error // error is an interface

Examples

package main

import "fmt"

func main() {
    var i int
    var f float64
    var b bool
    var s string
    fmt.Printf("%v %v %v %qn", i, f, b, s)
}

The output is:

0 0 false ""

Second method: determine the variable type based on the value.

var v_name = value

Examples

package main

import "fmt"

func main() {
    var d = true
    fmt.Println(d)
}

The output is:

true

Third method: if a variable has already been declared with var, using := to declare it again will cause a compile error. Format:

v_name := value

For example:

var intVal int
intVal := 1 // This will cause a compile error because intVal is already declared and doesn't need re-declaration

Use the following statement directly:

intVal := 1 // No compile error here because a new variable is declared; := is a declaration statement

intVal := 1 is equivalent to:

var intVal int
intVal = 1

You can shorten var f string = "" to f := "":

Examples

package main

import "fmt"

func main() {
    f := "" // var f string = ""
    fmt.Println(f)
}

The output is:

Multiple Variable Declarations

// Multiple variables of the same type, non-global
var vname1, vname2, vname3 type
vname1, vname2, vname3 = v1, v2, v3

var vname1, vname2, vname3 = v1, v2, v3 // Similar to Python, no explicit type declaration needed; type is inferred
vname1, vname2, vname3 := v1, v2, v3 // Variables on the left side of := should not have been declared before, otherwise it will cause a compile error

// This factored keyword syntax is generally used for declaring global variables
var (
    vname1 v_type1
    vname2 v_type2
)

Examples

package main

import "fmt"

var x, y int

var ( // This factored keyword syntax is generally used for declaring global variables
    a int
    b bool
)

var c, d int = 1, 2
var e, f = 123, "hello"

// This form without declaration can only appear inside a function body
// g, h := 123, "hello"

func main() {
    g, h := 123, "hello"
    fmt.Println(x, y, a, b, c, d, e, f, g, h)
}

The output of the above example is:

0 0 0 false 1 2 123 hello 123 hello

Value Types and Reference Types

All basic types like int, float, bool, and string are value types. Variables of these types point directly to the values stored in memory:

Image 1

When you use the assignment operator = to assign the value of one variable to another, like j = i, it actually copies the value of i in memory:

Image 2

You can get the memory address of variable i using &i, for example: 0xf840000040 (the address may vary each time).

Value type variables are typically stored on the stack, especially when they are local variables. When the value of a value type variable needs to be used outside the function scope, Go will allocate it to heap memory.

Memory addresses will differ based on the machine, and even the same program may have different memory addresses when executed on different machines. This is because each machine may have a different memory layout, and position allocation can also vary.

More complex data often requires multiple words, and this data is generally stored using reference types.

A reference type variable r1 stores the memory address (a number) where the value of r1 is located, or the location of the first word in that memory address.

Image 3

This memory address is called a pointer, and this pointer is actually stored in another value.

The multiple words pointed to by the pointer of the same reference type can be in contiguous memory addresses (the memory layout is contiguous), which is also the most efficient storage form; or these words can be scattered in memory, with each word indicating the memory address of the next word.

When using the assignment statement r2 = r1, only the reference (address) is copied.

If the value of r1 is changed, then all references to that value will point to the modified content. In this example, r2 will also be affected.


Short Form, Using the := Assignment Operator

We know that we can omit the variable type during variable initialization and let the system infer it. Writing the var keyword in the declaration statement seems somewhat redundant, so we can shorten them to a := 50 or b := false.

The types of a and b (int and bool) will be automatically inferred by the compiler.

This is the preferred form for using variables, but it can only be used inside a function body and cannot be used for global variable declaration and assignment. Using the := operator can efficiently create a new variable, known as a short variable declaration.

Notes

If within the same code block, we cannot use a short variable declaration for a variable with the same name again. For example, a := 20 is not allowed; the compiler will prompt the error no new variables on left side of :=. However, a = 20 is allowed because it assigns a new value to the same variable.

If you use a variable before defining it, you will get a compile error: undefined: a.

If you declare a local variable but do not use it within the same code block, you will also get a compile error, for example, the variable a in the following example:

Examples

package main

import "fmt"

func main() {
    var a string = "abc"
    fmt.Println("hello, world")
}

Trying to compile this code will result in the error a declared but not used.

Furthermore, simply assigning a value to a is not enough; the value must be used. So using

fmt.Println("hello, world", a)

will remove the error.

However, global variables are allowed to be declared but not used. Multiple variables of the same type can be declared on one line, like:

var a, b, c int

Multiple variables can be assigned on the same line, like:

var a, b int
var c string
a, b, c = 5, 7, "abc"

The above line assumes that variables a, b, and c have already been declared. Otherwise, it should be used like this:

a, b, c := 5, 7, "abc"

The values on the right are assigned to the variables on the left in the same order, so the value of a is 5, the value of b is 7, and the value of c is "abc".

This is called parallel or simultaneous assignment.

If you want to swap the values of two variables, you can simply use a, b = b, a. The types of the two variables must be the same.

The blank identifier _ is also used to discard values, such as the value 5 in _, b = 5, 7.

_ is actually a write-only variable; you cannot get its value. This is done because in Go, you must use all declared variables, but sometimes you don't need to use all return values from a function.

Parallel assignment is also used when a function returns multiple values, for example, here val and the error err are obtained simultaneously by calling the Func1 function: val, err = Func1(var1).

← Android Studio InstallGo Switch Statement β†’