类型、变量、函数
内建类型
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64
byte // alias for uint8
rune // alias for int32
float32 float64
complex32 complex64
类型转换
var i int = 42
var f float64 = float64(i)
var u uint = uint(f)
变量、常量定义
var foo int // 0
var foo int = 42
var foo, bar int = 42, 1302 // multiple
var foo = 42 // type inferred
foo := 42 // shorthand, only in func bodies
const bar = "This is a constant"
函数
func empty() {}
func empty(s string, c int) {}
func age() int {
return 32
}
func nameAndAge() (string, int) {
return "John", 32
}
func sum(args ...int) int {
total := 0
for _, v := range args {
total += v
}
return total
}
func generator(step int) func() int {
cur := 0
return func() int {
cur += step
return cur
}
}
func filter(f func(int) bool) bool {
return f(0)
}
控制流
if-else
if x > 0 {
x -= 1
} else {
x += 1
}
switch
switch operatingSystem {
case "darwin":
fmt.Println("Mac OS Hipster")
// cases break automatically, no fallthrough by default
case "linux":
fmt.Println("Linux Geek")
default:
// Windows, BSD, ...
fmt.Println("Other")
}
number := 42
switch {
case number < 42:
fmt.Println("Smaller")
case number == 42:
fmt.Println("Equal")
case number > 42:
fmt.Println("Greater")
}
for
for i := 0; i < 10; i++ {
}
for i < 10 {
}
for {
}
Array, Slice, Map
Array
var a [10]int // declare an int array with length 10. Array length is part of the type!
a[3] = 42 // set elements
i := a[3] // read elements
// declare and initialize
var a = [2]int{1, 2}
a := [2]int{1, 2} //shorthand
a := [...]int{1, 2} // elipsis -> Compiler figures out array length
Slice
var a []int // declare a slice - similar to an array, but length is unspecified
var a = []int {1, 2, 3, 4} // declare and initialize a slice (backed by the array given implicitly)
a := []int{1, 2, 3, 4} // shorthand
chars := []string{0:"a", 2:"c", 1: "b"} // ["a", "b", "c"]
var b = a[lo:hi] // creates a slice (view of the array) from index lo to hi-1
var b = a[1:4] // slice from index 1 to 3
var b = a[:3] // missing low index implies 0
var b = a[3:] // missing high index implies len(a)
a = append(a,17,3) // append items to slice a
c := append(a,b...) // concatenate slices a and b
// create a slice with make
a = make([]byte, 5, 5) // first arg length, second capacity
a = make([]byte, 5) // capacity is optional
// create a slice from an array
x := [3]string{"Лайка", "Белка", "Стрелка"}
s := x[:] // a slice referencing the storage of x
Array, Slice 遍历
for index, value := range a {
}
for _, value := range a {
}
for index := range a {
}
Map
var m map[string]int
m = make(map[string]int)
m["key"] = 42
fmt.Println(m["key"])
delete(m, "key")
elem, ok := m["key"] // test if key "key" is present and retrieve it, if so
// map literal
var m = map[string]Vertex{
"Bell Labs": {40.68433, -74.39967},
"Google": {37.42202, -122.08408},
}
for key, value := range m {
fmt.Println("Key:", key, "Value:", value)
}