You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
interface {} // ~ java Objectbool// true/falsestringint8int16int32int64int// =int32 on 32-bit, =int64 if 64-bit OSuint8uint16uint32uint64uintptruintbyte// alias for uint8rune// alias for int32, represents a Unicode code pointfloat32float64
Zero value (i.e. default value)
0 for numeric types.
false for the boolean type.
"" (the empty string) for strings.
Type casting
T(v): type conversion, convert v to type Tobj.(T): type assertion, obj must be interface{} (i.e. unknown type).
t:=obj.(T) // if obj is not T, errort, ok:=obj.(T) // if obj is not T, ok = false
Variable declaration
Normal form:
var id1, id2,...type
var id1, id2,...type = value1, value2,...
var id1, id2,... = value1, value2,... (implicit type)
var a, b int
var c, d int = 1, 2
var e, f, g = 3, 4, 5
d := 3
Initialization
new(Type) allocates memory with default value and returns its address.
make(Type, args) init object of type Type (Type must be slice, map, or channel).
varp*Person=new(Person) // pointer of type Personvars []int=make([]int, 10) // slice of int
Array and slice
Array is a value (assigning = copying).
Slice is a wrapper of an array (keeps a reference to the wrapped array).
(Using slice is strongly recommended because it is convenient)
vararr= [3]int{1, 2, 3, 4} // an array. Length 3 inside [] is requiredarr:= [...]int{1, 2, 3, 4} // same as aboveslice:=make([]int, 3) // a slice of {0, 0, 0}slice= []int{1, 2, 3, 4} // a slice of array {1, 2, 3, 4}. NO length inside []slice=arr[1:] // = []int{2, 3, 4}, slicing an array
Map
map[key Type]value Type
(key can be any type that defined the equality operator (primitive types and struct))
varmyMap=map[string]int {
"one": 1,
"two": 2
}
v:=myMap["one"] // 1v=myMap["three"] // not exist, returns zero/default value. In this case, 0v, ok:=myMap["three"] // not exist, v = 0, ok = falsedelete(myMap, "two") // delete entry
If
if condition
ifx<10 {}
if init; condition
if x = 1; x < 10 {}
For
for init; condition; post
for condition (~ while)
for {} (loop 4ever)
for id := range collection (~ for each)
fori:=0; i<10; i++ {}
fortrue {}
for {}
forkey, value:=rangemyMap {} // ~ for each
Switch
switch obj {} (no need to be const)
switch {} (pseudo if-else)
funcdivide(aint, bint) (int) {}
// named return param, `rs` is init as a variablefuncdivide(aint, bint) (rsint) {}
Defer
defer doSth(): defer statement, schedules to run doSth() before return
funcread(...) (...) {
f, err:=os.Open(file)
...deferf.Close()
...return .. // f will be closed
Struct
import"fmt"typePersonstruct {
namestringageint
}
// Create some methods for Personfunc (pPerson) walk() {
}
func (p*Person) walk() {
}
p:=Person{"John", 20} // auto constructorpt:=&pfmt.Println(p.name)
fmt.Println(pt.name) // Field accessing also works with pointerp.walk()
pt.walk() // Same as calling methods
Const/Enum
const (
USERNAME="a"PASSWORD=123
)
Struct embedding
There is no inheritance in Go. But you can embed other types into your custom type (~ sub-classing).
typeRunnerstruct {
speedint
}
func (r*Runner) Run() {
fmt.Println("run at", r.speed)
}
typeBarkerstruct {
volumeint
}
func (b*Barker) Bark() {
fmt.Println("bark at", b.volume)
}
typeHuskystruct {
*Runner// Husky can now run*Barker// Husky can now bark
}
// constructor of Husky now receive 2 pointers to 2 embedded typesdog:=Husky{ &Runner{10}, &Barker{2} }
fmt.Println(dog.speed) // can access embedded-type propertydog.Run() // can access embedded-type methoddog.Bark() // however, the receiver of the method Bark() is Barker not Husky
Goroutine
Is a lightweight thread. Keyword go
godoSth() // run doSth() concurently
Channel
A pipe that connects goroutines. Used to send and receive values.
cn=make(chanstring) // channel of type stringfuncmain() {
cn=make(chanstring) // channel of type string// send value into the channel (1)gofunc() { cn<-"ping" }()
// receive message from the channelmsg:=<-cn// Sends and receives block until both are done.// after receiving, func (1) will continue
}
Buffered channel allows sending multiple messages before receiving.