slices _ golang

Slices are a key data type in Go, giving a more powerful interface to sequences than arrays

package main

import (
    "fmt"
)

func main() {

    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))

    s = append(s, "d")
    s = append(s, "e", "f")
    fmt.Println("apd : ", s)

    c := make([]string, len(s))
    copy(c, s)
    fmt.Println("cpy : ", c)

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

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

    l = s[2:]
    fmt.Println("sl3 :", 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)

}
emp: [  ]
set :  [a b c]
get :  c
len : 3
apd :  [a b c d e f]
cpy :  [a b c d e f]
sl1 :  [c d e]
sl2 : [a b c d e]
sl3 : [c d e f]
dcl : [g h i]
2d :  [[0] [1 2] [2 3 4]]

总结 : 

  1 : 到这里要感慨一下, golang 是好, 好在语法简单

  2 :  slices 的声明, 奇怪啊!  s := make([]string, 3)   (YY python的slice呢...)

  3 :  slices de copy (cpoy(c, s))

  4 :  .....

原文地址:https://www.cnblogs.com/jackkiexu/p/4335117.html