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?
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.
:= 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With