// declare variable name of foo with int type var foo int // assign only foo = 10 // declare variable and assign var foo int foo = 10 var foo int = 10 // implicit var foo = 32 // shorthand for declare and assign foo := 10
You cannot use short variable declaration outside a function
// illegal package main n := 1 func main() {} // legal package main var n = 1 func main() {}
;
)// semicolon syntax if err := failFunction(); err != nil { log.Fatal(err) } // can be rewritten as block scope { err := failFunction() if err != nil { log.Fatal(err) } }
The outer {}
brackets act as a block which creates a new scope.
When err
is defined before the block scope, a new variable named err
will be created inside the new scope will override the value of previously defined err
until the end of block scope.
Cannot be declared using the :=
syntax
const ConstantValue = "cannot change" const ( imageWidth = 160 jpegQuality = 50 )