1. 程式人生 > >Go Example--切片

Go Example--切片

package main

import (
    "fmt"
)

func main()  {
    //make來初始化一個切片,必須指名切片的長度
    s:= make([]string, 3)
    fmt.Println("emp:",s)

    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    fmt.Println("set:",s)
    fmt.Println("get:",s[2])
    fmt.Println("len:",len(s))

    //append函式向切片尾部新增值,切片長度不夠時,會重新申請記憶體給s
    s = append(s, "d")
    s = append(s,"e","f")
    fmt.Println("apd:",s)

    c:=make([]string,len(s))
    //copy是在記憶體中複製s到c
    copy(c,s)
    fmt.Println("cpy:",c)

    //l和s均指向相同的底層陣列
    l:=s[2:5]
    fmt.Println("sl1:",l)

    l=s[:5]
    fmt.Println("sl1:",l)
    l=s[2:]
    fmt.Println("sl1:",l)

    t:=[]string{"g","h","i"}
    fmt.Println("dcl:",t)

    //二維切片,
    twoD := make([][]int,3)
    for i:=0; i<3;i++  {
        innerLen := i+1;
        //內部需要重新申請記憶體
        twoD[i] = make([]int,innerLen)
        for j:=0;j<innerLen ;j++  {
            twoD[i][j] =i+j
        }
    }
    fmt.Println("2d: ",twoD)
}