Basic Concepts Flashcards
Packages
Programs start running in package main.
package main
import (
“fmt”
“math/rand”
)
func main() { }
Imports
import ( "fmt" "math" ) -OR- import "fmt" import "math"
Exported names
After importing a package, you can refer to the names it exports.
In Go, a name is exported if it begins with a capital letter.
Functions
func add(x int, y int) int { return x + y } -OR- When two or more consecutive named function parameters share a type, you can omit the type from all but the last.
func add(x, y int) int { return x + y }
Multiple results
func swap(x, y string) (string, string) { return y, x }
Named results
If the result parameters are named, a return statement without arguments returns the current values of the results.
func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return }
Variables
var x, y, z int
var c, python, java bool
Variables with initializers
A var declaration can include initializers, one per variable.
If an initializer is present, the type can be omitted; the variable will take the type of the initializer.
var x, y, z int = 1, 2, 3
var c, python, java = true, false, “no!”
Short variable declarations
:=
Inside or outside available?
Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.
Outside a function, every construct begins with a keyword (var, func, and so on) and the := construct is not available.
func main() { var x, y, z int = 1, 2, 3 c, python, java := true, false, "no!"
fmt.Println(x, y, z, c, python, java) }
Go’s basic types are
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
Constants
Constants are declared like variables, but with the const keyword.
Constants can be character, string, boolean, or numeric values.
Constants cannot be declared using the := syntax.
const Pi = 3.14
Numeric Constants
Numeric constants are high-precision values.
An untyped constant takes the type needed by its context.
const (
Big = 1 «_space;100
Small = Big»_space; 99
)
For Loop
Go has only one looping construct, the for loop.
The basic for loop looks as it does in C or Java, except that the ( ) are gone (they are not even optional) and the { } are required.
sum := 0 for i := 0; i < 10; i++ { sum += i }
For continued
As in C or Java, you can leave the pre and post statements empty.
sum := 1 for ; sum < 1000; { sum += sum }
For is Go’s “while”
At that point you can drop the semicolons: C’s while is spelled for in Go.
sum := 1 for sum < 1000 { sum += sum }