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 :  .....

本文来自:博客园

感谢作者:jackkiexu

查看原文:slices _ golang

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。