Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this parenthesis enclosed variable declaration syntax in 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?

like image 760
Patryk Avatar asked Mar 06 '16 18:03

Patryk


People also ask

What is () before function name in Golang?

The parenthesis before the function name is the Go way of defining the object on which these functions will operate. So, essentially ServeHTTP is a method of type handler and can be invoked using any object, say h, of type handler.

What is the := IN go?

:= is known as the short declaration operator. It is used to declare and initialize the variables inside and outside the functions. It is used to declare and initialize the variables only inside the functions.

What is variable declaration Golang?

Short Variable Declaration Operator(:=) in Golang is used to create the variables having a proper name and initial value. The main purpose of using this operator to declare and initialize the local variables inside the functions and to narrowing the scope of the variables.


2 Answers

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.

like image 145
Nick Craig-Wood Avatar answered Nov 16 '22 01:11

Nick Craig-Wood


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.

like image 26
Ben Darnell Avatar answered Nov 16 '22 02:11

Ben Darnell