英文:
What is this parenthesis enclosed variable declaration syntax in Go?
问题
我正在尝试找到关于Go语言中括号括起来的变量声明语法的信息,但可能是因为我不知道它的名称,所以找不到(就像值和指针接收器一样)。
具体来说,我想知道这种语法背后的规则是什么:
package main
import (
"path"
)
// 这种语法是什么?它是可导出的吗?
var (
rootDir = path.Join(home(), ".coolconfig")
)
func main() {
// 无论什么内容
}
在导入此模块的模块中,var ()
块中的变量是否可用?
英文:
I am trying to find some information on parenthesis enclosed variable declaration syntax in Go but maybe I just do not know its name and that's why I cannot find it (just like with e.g. value and pointer receivers).
Namely I would like to know the rules behind this type of syntax:
<!-- language: lang-go -->
package main
import (
"path"
)
// What's this syntax ? Is it exported ?
var (
rootDir = path.Join(home(), ".coolconfig")
)
func main() {
// whatever
}
Are those variables in var ()
block available in modules that import this one?
答案1
得分: 26
这段代码
// 这是什么语法?它是被导出的吗?
var (
rootDir = path.Join(home(), ".coolconfig")
)
只是写成更长的形式
var rootDir = path.Join(home(), ".coolconfig")
然而,在一次声明多个变量时,这种写法很有用。而不是
var one string
var two string
var three string
你可以写成
var (
one string
two string
three string
)
同样的技巧也适用于 const
和 type
。
英文:
This code
// What's this syntax ? Is it exported ?
var (
rootDir = path.Join(home(), ".coolconfig")
)
is just a longer way of writing
var rootDir = path.Join(home(), ".coolconfig")
However it is useful when declaring lots of vars at once. Instead of
var one string
var two string
var three string
You can write
var (
one string
two string
three string
)
The same trick works with const
and type
too.
答案2
得分: 10
var (...)
(以及const (...)
)只是一种简写方式,可以避免重复使用var
关键字。对于单个变量来说,这样做可能没有太多意义,但如果你有多个变量,用这种方式分组会更美观。
这与导出无关。以这种方式声明的变量是否导出取决于它们名称的大小写,就像没有使用括号声明的变量一样。
英文:
var (...)
(and const (...)
are just shorthand that let you avoid repeating the var
keyword. It doesn't make a lot of sense with a single variable like this, but if you have multiple variables it can look nicer to group them this way.
It doesn't have anything to do with exporting. Variables declared in this way are exported (or not) based on the capitalization of their name, just like variables declared without the parentheses.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论