douyun3887 2016-03-06 18:20
浏览 385
已采纳

Go中用括号括起来的变量声明语法是什么?

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:

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?

  • 写回答

2条回答 默认 最新

  • dscw1223 2016-03-06 18:25
    关注

    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 too.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写uniapp时遇到的问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流