七.Go切片slice

2017-06-18  本文已影响0人  kaxi4it

切片slice

func main() {
    ary := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    s1 := ary[3:8]
    s2 := ary[5:8]
    //[4 5 6 7 8] 5 7
    fmt.Println(s1, len(s1), cap(s1))
    //[6 7 8] 3 5
    fmt.Println(s2, len(s2), cap(s2))

    s2[0] = 0
    //[4 5 0 7 8] 5 7
    fmt.Println(s1, len(s1), cap(s1))
    //[0 7 8] 3 5
    fmt.Println(s2, len(s2), cap(s2))

    s3 := make([]int, 3, 10)
    //[0 0 0] 3 10
    fmt.Println(s3, len(s3), cap(s3))
}

Reslice

func main() {
    s4 := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    s5 := s4[3:7]
    s6 := s5[1:3]
    //[4 5 6 7] 4 7
    fmt.Println(s5, len(s5), cap(s5))
    //[5 6] 2 6
    fmt.Println(s6, len(s6), cap(s6))
}

Append

func main() {
    s7 := []int{1, 2, 3, 4, 5}
    s8 := s7[1:3]
    s9 := s7[2:4]
    //[3 4] 0x1234d828
    fmt.Printf("%v %p\n", s9, s9)
    s9 = append(s9, 1)
    //[3 4 1] 0x1234d828
    fmt.Printf("%v %p\n", s9, s9)
    s9 = append(s9, 2)
    //[3 4 1 2] 0x1234d840
    fmt.Printf("%v %p\n", s9, s9)
    //[3 4 1 2 2 3] 0x122fd840
    s9 = append(s9, s8...)
    fmt.Printf("%v %p\n", s9, s9)
}

Copy

func main() {
    c1 := []int{1, 2, 3, 4, 5}
    c2 := []int{8, 7, 6, 5, 4, 3, 2, 1}
    copy(c1, c2)
    //[8 7 6 5 4]
    fmt.Println(c1)
    c3 := []int{1, 2, 3, 4, 5}
    c4 := []int{8, 7, 6, 5, 4, 3, 2, 1}
    copy(c4, c3)
    //[1 2 3 4 5 3 2 1]
    fmt.Println(c4)
    c5 := []int{1, 2, 3, 4, 5}
    c6 := []int{8, 7, 6, 5, 4, 3, 2, 1}
    copy(c5[2:4], c6[1:3])
    //[1 2 7 6 5]
    fmt.Println(c5)
}

直通车

一.Go开发工具及命令
二.Go编程基础知识
三.Go的类型与变量
四.Go常量与运算符
五.Go控制语句
六.Go数组
七.Go切片slice
八.Go哈希字典map
九.Go函数func
十.Go结构struct

上一篇下一篇

猜你喜欢

热点阅读