Variable Declarations
To declare a variable in Go, you use the var keyword followed by the variable name and type:
var x intThe type is optional if you are initializing the variable and the compiler can infer the type:
var x = 10However, you can still be explicit:
var x int = 10Unlike JavaScript, var creates a block scoped variable in Go, similar to let in JavaScript. There is no var like JavaScript equivalent in Go (no way to create function scoped variables), all variables in Go are block scoped.
A note on uninitialized variables
Section titled “A note on uninitialized variables”While in JavaScript, uninitialized variables are set to undefined, in Go, they are set to the zero value of their type.
The zero value differs by type:
int:0float64:0.0string:""(empty string)bool:false[]T:nil(empty slice)map[K]V:nil(empty map)chan T:nil(empty channel)
Constants
Section titled “Constants”Constants are declared using the const keyword:
const pi = 3.14 // Declare a constantShorthand Declaration
Section titled “Shorthand Declaration”You will often see the following shorthand declaration := in Go:
x := 10 // Declare and initialize an int variablethis is equivalent to:
var x int = 10 // Declare and initialize an int variableConstants cannot be declared using the shorthand declaration.
It’s most often used in places with multiple return values:
file, err := os.Open("filename.txt")if err != nil { // handle error}// use fileWithout the shorthand, it would need to look like this:
var file *os.Filevar err errorfile, err = os.Open("filename.txt")if err != nil { // handle error}// use fileHowever you can use the shorthand also with ordinary values:
x, y, z := 1, "hello", trueMultiple Declarations
Section titled “Multiple Declarations”You can declare multiple variables at once using the following syntax:
var ( x int y string z bool)This is equivalent to:
var x intvar y stringvar z boolIf they all share the same type, you even shorten it further:
var x, y, z intThis is equivalent to:
var x intvar y intvar z int