Pat*_*ryk 7 variables syntax declaration go
我试图在Go中找到关于括号括起的变量声明语法的一些信息,但也许我只是不知道它的名字,这就是为什么我找不到它(就像例如值和指针接收器一样).
即我想知道这种语法背后的规则:
package main
import (
"path"
)
// What's this syntax ? Is it exported ?
var (
rootDir = path.Join(home(), ".coolconfig")
)
func main() {
// whatever
}
Run Code Online (Sandbox Code Playgroud)
这些变量是否在var ()
导入此模块的模块中可用?
Nic*_*ood 13
这段代码
// What's this syntax ? Is it exported ?
var (
rootDir = path.Join(home(), ".coolconfig")
)
Run Code Online (Sandbox Code Playgroud)
只是一种较长的写作方式
var rootDir = path.Join(home(), ".coolconfig")
Run Code Online (Sandbox Code Playgroud)
但是,在一次声明大量变量时很有用.代替
var one string
var two string
var three string
Run Code Online (Sandbox Code Playgroud)
你可以写
var (
one string
two string
three string
)
Run Code Online (Sandbox Code Playgroud)
同样的伎俩也适用const
.
var (...)
(和const (...)
只是速记,让你避免重复的var
关键字.它没有很大的意义,像这样一个变量,但如果你有多个变量可以更好看他们这样一群.
它与导出没有任何关系.以这种方式声明的变量是基于其名称的大小写导出(或不导出),就像没有括号声明的变量一样.