类型、变量、函数
内建类型
boolstringint int8 int16 int32 int64uint uint8 uint16 uint32 uint64byte // alias for uint8rune // alias for int32float32 float64complex32 complex64
类型转换
var i int = 42var f float64 = float64(i)var u uint = uint(f)
变量、常量定义
var foo int // 0var foo int = 42var foo, bar int = 42, 1302 // multiplevar foo = 42 // type inferredfoo := 42 // shorthand, only in func bodiesconst 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 defaultcase "linux": fmt.Println("Linux Geek")default: // Windows, BSD, ... fmt.Println("Other")}number := 42switch {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 elementsi := a[3] // read elements// declare and initializevar a = [2]int{1, 2}a := [2]int{1, 2} //shorthanda := [...]int{1, 2} // elipsis -> Compiler figures out array length
Slice
var a []int // declare a slice - similar to an array, but length is unspecifiedvar a = []int {1, 2, 3, 4} // declare and initialize a slice (backed by the array given implicitly)a := []int{1, 2, 3, 4} // shorthandchars := []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-1var b = a[1:4] // slice from index 1 to 3var b = a[:3] // missing low index implies 0var b = a[3:] // missing high index implies len(a)a = append(a,17,3) // append items to slice ac := append(a,b...) // concatenate slices a and b// create a slice with makea = make([]byte, 5, 5) // first arg length, second capacitya = make([]byte, 5) // capacity is optional// create a slice from an arrayx := [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]intm = make(map[string]int)m["key"] = 42fmt.Println(m["key"])delete(m, "key")elem, ok := m["key"] // test if key "key" is present and retrieve it, if so// map literalvar 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)}