2022年2月7日 星期一

Go lang 學習筆記 - 9 Slices

 ```

package main


import "fmt"


func main() {

        s := make([]string, 3)

        s[0] = "a"

        s[1] = "b"

        s[2] = "c"


        fmt.Println("set: ", s)

        fmt.Println("get: ", s[2])

        fmt.Println("len: ", len(s))


        s = append(s, "d")

        s = append(s, "e", "f")

        fmt.Println("apd: ", s)


        c := make([]string, len(s))

        copy(c, s)

        fmt.Println("copy: ", c)


        l := s[2:5]

        fmt.Println("slic1: ", l)


        l = s[:5]

        fmt.Println("slic2: ", l)


        l = s[2:]

        fmt.Println("slic3: ", l)

        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)

}

```

Slice 的操作跟 Python 的用法很相似

比較特別的是用 make 先產生固定長度的 array (有點像是 C++ 的 new 但不需要delete )

然後在二維陣列(2D array)的 make 第二個參數指定的只有第一層的長度

內層 array 的長度可以不一樣


執行結果:

set:  [a b c]

get:  c

len:  3

apd:  [a b c d e f]

copy:  [a b c d e f]

slic1:  [c d e]

slic2:  [a b c d e]

slic3:  [c d e f]

2D:  [[0] [1 2] [2 3 4]]

沒有留言:

張貼留言

Go lang 學習筆記 - 17 Pointers

``` package main import "fmt" func zeroval(n int) {         n = 0 } func zeroptr(n *int) {         *n = 0 } func main() {         ...