Convention in Go is to use MixedCaps
or mixedCaps
rather than underscores to write multiword names.
Capitalized identifiers are exported from a package.
// 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
Shorthand variable declaration always infers the type.
You cannot use short variable declaration outside of a function.
// illegal package main n := 1 // shorthand cannot be outside func func main() {} // legal package main var n = 1 // declared using var instead func main() {}
Go does not hoist the variables to the top of the context.
Go requires that variables be declared before they are used, and it cannot be referenced before declaration.
Variables in Go are scoped to the block
in which they are declared.
A variable can be redeclared
in an inner scope, effectively shadowing the outer variable with the same name.
package main import "fmt" someVal := "1" func main() { var someVal = "2" // valid shadow fmt.Sprintf(someVal) // "2" }
Global scope
is same as a package scope
.
A variable
, function
, or type
declared at the package level
(outside of any function or block) is available throughout the entire package
.
When you capitalize
identifiers, they are exported from a package
.
public
notExportedMember := "1" ExportedMember := "2" func unexportedFunc() { // ... } func ExportedFunc() { // ... }
Variables declared inside a function block are always private
, or unexported
.
Package names
do not have to be capitalized when imported and used.
package main // package names are referenced lowercase import "sample/example" // example package is lowercase // PublicMember has to be uppercase m := example.PublicMember()
De-reference is
fmt.Println(*ptr)
Cannot de-reference to null
value.
;
)// 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.
Constants cannot be declared using the :=
syntax
const ConstantValue = "cannot change" const ( imageWidth = 160 jpegQuality = 50 )