Variables
Naming Convention
Convention in Go is to use MixedCaps
or mixedCaps
rather than underscores to write multiword names.
Capitalized identifiers are exported from a package.
Variable Declarations
// 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
Shorthand variable declaration always infers the type.
- You cannot specify the type using shorthand
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() {}
Hoisting
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.
Scope
Variables in Go are scoped to the block
in which they are declared.
- Variables declared within a function are not accessible outside that function and only exist during execution of the function.
Shadow Variables
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
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
.
Exported Variables
When you capitalize
identifiers, they are exported from a package
.
- same as a
public
- applies to variables, types, and functions
notExportedMember := "1" ExportedMember := "2" func unexportedFunc() { // ... } func ExportedFunc() { // ... }
Variables declared inside a function block are always private
, or unexported
.
- Capitalization has no effects in this case.
Exported Variable vs Package Name
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()
Pointer and Reference
Reference
De-reference
De-reference is
fmt.Println(*ptr)
Cannot de-reference to null
value.
Semicolon (;
)
// 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
Constants cannot be declared using the :=
syntax
const ConstantValue = "cannot change" const ( imageWidth = 160 jpegQuality = 50 )