抽空看了一下go,顺便做了个总结。话说go的语法还真感觉有点特别,而且抽象层次更高,对初学者可能障碍更多。还是按照之前的套路,我做了一个简化版的go语言语法小结,仅供参考。

参考资料:

变量声明定义的三种方式
var a int
a = 10

var a = 10

// 只能用在函数体内
a := 10
数据类型

bool

var b = true

if b {
    fmt.Println("This is true")
}

slice

    /* Format 1 */
    var p = []int{2, 3, 5, 7, 11, 13}
    fmt.Println("p ==", p)
    for i := 0; i < len(p); i++ {
        fmt.Printf("p[%d] == %d\n", i, p[i])
    }

    /* Format 2 */
    var a []int
    if a == nil {
        fmt.Println("nil!")
    }
    a = make([]int, 5, 5)
    a[0] = 1

    /* Format 3 */
    b := make([]int, 0, 5)

map

    type Vertex struct {
        Lat, Long float64
    }

    var m map[string]Vertex
    m = make(map[string]Vertex)
    m["Bell Labs"] = Vertex{
        40.68433, -74.39967,
    }
    m["AT&T Labs"] = Vertex{
        40.68433, -74.39967,
    }
    fmt.Println(m["Bell Labs"])

    v, ok := m["AT&T Labs"]
    if ok {
        fmt.Println(v)
    } else {
        fmt.Println("No such element")
    }

    delete(m, "AT&T Labs")

    v, ok = m["AT&T Labs"]
    if ok {
        fmt.Println(v)
    } else {
        fmt.Println("No such element")
    }
控制语句

for

    var sum int
    sum = 0
    for i := 0; i < 10; i++ {
        sum += i
    }
    fmt.Println(sum)

    sum = 1
    for sum < 1000 {
        sum += sum
    }
    fmt.Println(sum)

    var a [10]int
    for i, val := range a {
        fmt.Printf("Value[%d] %d\n", i, val)
    }

    for _, val := range a {
        fmt.Println("Value ", val)
    }

if

    if age > 18 {
        fmt.Println("Adult")
    } else if age > 3 {
        fmt.Println("Child")
    } else {
        fmt.Println("Elphan")
    }
函数定义

函数

func sum(a int, b int) int {
    return a + b
}

多返回值

func swap(x, y string) (string, string) {
    return y, x
}

a, b = swap("hello", "world")
fmt.Println(a, b)

多返回值2

func concat(x, y string) (int, string) {
    return len(x + y), x + y
}

length, _ = concat("hello ", "world")
fmt.Println(length)

闭包函数

如果对c语言有深入研究,闭包函数其实就是函数+静态变量。

package main

import "fmt"

func fibonacci() func() int {
    /* use -1 to indicate the value is uninitialized */
    gp, p, fib := -1, -1, 0
    return func() int {
        if p == -1 {
            p = 0
            return 0
        } else if gp == -1 {
            p = 1
            gp = 0
            return 1
        }

        fib = gp + p
        gp = p
        p = fib
        return fib
    }
}

func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}

方法

type Circle struct {
    radius float64
}

func (c Circle) getArea() float64 {
    return 3.14 * c.radius * c.radius
}

var c1 Circle
c1.radius = 10.0
fmt.Println(c1.getArea())