A Tour of Go - Basics: Packages, variables, and functions. Flashcards
Go programs are made up of …
packages
Which package do Go programs start in?
main
By convention, the package name is the …
last element of the import path
Give an example of a package statement?
package main
Give and example of an import statement?
import "fmt"
Give and example of a factored import statement?
import ( "fmt" "math/rand" )
Factored import statements are considered good style.
What is an exported name?
In Go, and exported name begins with a capital letter.
When importing a package you can only refer to the exported names.
Give an example of a function that adds two integers?
func add(x, y int) int { return x + y }
Function can return multiple results
Give an example of a function that swaps two strings?
func swap(x, y string) (string, string) { return y, x }
What is a naked return?
Go’s return values can be named. If so, they are treated as variables defined at the top of the function.
A return statement with no arguments will return the names return values.
Describe the var
statement.
The var
statement declares a list of variables, the type is last.
A var statement can be used at package or function level.
var i, j int var s string
What is an initaliser?
A var declaration can include initialisers, one per variable.
If an initialiser is present, the type can be omitted; the variable will take the type of the initialiser.
var i int = 1 var s = "hello"
What is a short variable declaration?
In functions, the :=
short assignment statement can be used in place of a var
declaration with implicit type.
i, j := 1, 2 s := "hello"
What are Go’s basic types?
bool string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr byte // alias for uint8 rune // alias for int32 // represents a Unicode code point float32 float64 complex64 complex128
What is a zero value?
Variables declared without an explicit initial value are given their zero value.
The zero value is:
- 0 for numeric types,
- false for the boolean type, and
- ”” (the empty string) for strings.