SoFunction
Updated on 2025-03-05

Go language variable definition usage example

This article describes the usage of go language variable definitions. Share it for your reference. The details are as follows:

The var statement defines a list of variables; like the list of parameter of a function, the type is followed.

Copy the codeThe code is as follows:
package main
import "fmt"
var x, y, z int
var c, python, java bool
func main() {
    (x, y, z, c, python, java)
}

A variable definition can contain an initial value, and each variable corresponds to one.

If initialization is using an expression, the type can be omitted; the variable obtains the type from the initial value.

Copy the codeThe code is as follows:
package main
import "fmt"
var x, y, z int = 1, 2, 3
var c, python, java = true, false, "no!"
func main() {
    (x, y, z, c, python, java)
}

In a function, the := concise assignment statement can be used instead of the var definition where the type is explicit.

(:= structure cannot be used outside the function, and every syntax block outside the function must start with a keyword.)

Copy the codeThe code is as follows:
package main
import "fmt"
func main() {
    var x, y, z int = 1, 2, 3
    c, python, java := true, false, "no!"
    (x, y, z, c, python, java)
}

I hope this article will be helpful to everyone's Go language programming.