golang 变量声明

前端之家收集整理的这篇文章主要介绍了golang 变量声明前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

In Go,variablesare explicitly declared and used by the compiler to e.g. check type-correctness of function calls.

package main
import "fmt"
func main() {

vardeclares 1 or more variables.

var a string = "initial" fmt.Println(a)

You can declare multiple variables at once.

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

Go will infer the type of initialized variables.

var d = true fmt.Println(d)

Variables declared without a corresponding initialization arezero-valued. For example,the zero value for anintis0.

var e int fmt.Println(e)

The:=Syntax is shorthand for declaring and initializing a variable,e.g. forvar f string = "short"in this case.

f := "short" fmt.Println(f) }

$ go run variables.go initial 1 2 true 0 short

In Go,top-level variable assignmentsmustbe prefixed with thevarkeyword. Omitting thevarkeyword is only allowed within blocks.

package main

var toplevel = "Hello world"         // var keyword is required

func F() {
        withinBlock := "Hello world" // var keyword is not required
}

猜你在找的Go相关文章