Variable Declarations
To declare a variable in Go, you use the var
keyword followed by the variable name and type:
var x int
The type is optional if you are initializing the variable and the compiler can infer the type:
var x = 10
However, you can still be explicit:
var x int = 10
Unlike 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
:0
float64
:0.0
string
:""
(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 constant
Shorthand Declaration
Section titled “Shorthand Declaration”You will often see the following shorthand declaration :=
in Go:
x := 10 // Declare and initialize an int variable
this is equivalent to:
var x int = 10 // Declare and initialize an int variable
Constants 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 file
Without 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 file
However you can use the shorthand also with ordinary values:
x, y, z := 1, "hello", true
Multiple 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 bool
If they all share the same type, you even shorten it further:
var x, y, z int
This is equivalent to:
var x intvar y intvar z int