Go基础语法练习(1)


package main

import (
    "fmt"
    "strconv"
)

func main() {
    zTest()
    fibo()
    strTest()
    arrayTest()
    sliceTest()
    mapTest()
    a, b, c := funTest(1, 3, "Code ")
    fmt.Println(a, b, c)

}

func funTest(a int, b int, c string) (int, bool, string) {
    s := a + b
    if s > 0 {
        return s, true, c + "Yes"
    } else {
        return s, false, c + "No"
    }
}

func mapTest() {
    m1 := map[int]string{1: "A", 2: "B", 3: "C"}
    fmt.Println(m1)
    for k, v := range m1 {
        fmt.Println(k, v)
    }
    // 分配空间
    m2 := make(map[int]string, 10)
    for i := 0; i < 10; i++ {
        m2[i] = "a" + strconv.Itoa(i)
    }
    fmt.Println(m2)
    for j := 0; j < 11; j++ {
        v, ok := m2[j]
        if ok {
            fmt.Println("key=", j, "value=", v)
        } else {
            fmt.Println("key=", j, "value不存在!!!")
        }
    }
}

func zTest() {
    name := "zj"
    p := &name
    *p = "make"
    fmt.Println("name:", *p)
    fmt.Println("name ptr", &p)
}

func fibo() {
    a := 0
    b := 1
    for i := 1; i <= 30; i++ {
        fmt.Println(i, a)
        a, b = b, a+b
    }
}

func strTest() {
    context_body := `./a.out <option>
-h hlep
-a all`
    fmt.Println(context_body)
    fmt.Println(len(context_body))
}

func arrayTest() {
    nums1 := [5]int{1, 2, 3, 4, 5}
    for i, v := range nums1 {
        fmt.Println(i, v)
    }
}

func sliceTest() {
    // 不定长数组
    city := []string{"Beijing", "Shanghai", "Guangzhou", "Shenzhen"}
    city = append(city, "Hangzhou")
    city = append(city, "Nanjing")
    city = append(city, "Chongqing")
    //city = append(city, "Xian")
    //city = append(city, "Chengdu")
    // cap 当添加元素超出当前容量时 容量×2
    city1 := city[3:]
    fmt.Println(city, len(city), cap(city))
    fmt.Println(city1, len(city1), cap(city1))
    // 指定切片的容量,make(类型,长度,容量)
    s1 := make([]string, len(city))
    fmt.Println(s1, len(s1), cap(s1))
    // [:]将数组变为切片, copy接受的类型为切片
    copy(s1, city[:])
    fmt.Println(s1, len(s1), cap(s1))
}