20_Go基础(slice)

package main

import (
    "fmt"
)

func main() {
    // 定义 切片不保存具体的值
    s1 := []string{}
    s2 := []int{0, 1, 2, 3, 4, 5}

    fmt.Println(s1, s2)
    fmt.Println(s1 == nil) // false

    // 长度和容量 注意截取方式不同,容量的不同
    s3 := s2[2:]
    fmt.Println(s3)                                  // [2 3 4 5]
    fmt.Printf("s3长度:%d,容量: %d
", len(s3), cap(s3)) // 长度:4,容量: 4

    s4 := s3[2:]
    fmt.Println(s4)                                  // [4 5]
    fmt.Printf("s4长度:%d,容量: %d
", len(s4), cap(s4)) // s4长度:2,容量: 2

    s5 := s3[:2]
    fmt.Println(s5)                                  // [2 3]
    fmt.Printf("s5长度:%d,容量: %d
", len(s5), cap(s5)) // s5长度:2,容量: 4

    s6 := s3[1:3]
    fmt.Println(s6)                                  // [3 4]
    fmt.Printf("s6长度:%d,容量: %d
", len(s6), cap(s6)) // s5长度:2,容量: 3

    s7 := s2[2:4]
    fmt.Println(s7)                                  // [2 3]
    fmt.Printf("s7长度:%d,容量: %d
", len(s7), cap(s7)) // s7长度:2,容量: 4

    // 切片修改
    s4[0] = 100
    fmt.Println(s4) // [100 5]
    fmt.Println(s3) // [2 3 100 5]
    fmt.Println(s2) // [0 1 2 3 100 5]
    s2[5] = 99
    fmt.Println(s2) // [0 1 2 3 100 99]
    fmt.Println(s3) // [2 3 100 99]
    fmt.Println(s4) // 100 99]

    // make 创建切片
    s8 := make([]int, 5, 10) // s8: len=5, cap=10, val=[0 0 0 0 0]
    fmt.Printf("s8: len=%d, cap=%d, val=%v
", len(s8), cap(s8), s8)
    s9 := make([]string, 0)
    if len(s9) == 0 {
        fmt.Println("s9 是空切片")
    }

    // append 追加元素
    s10 := []int{0, 1, 2, 3, 4, 5}
    s11 := s10[2:]
    fmt.Printf("s11: len=%d, cap=%d, val=%v
", len(s11), cap(s11), s11)
    // s11: len=4, cap=4, val=[2 3 4 5]
    s11 = append(s11, 6)
    fmt.Printf("s10: len=%d, cap=%d, val=%v
", len(s10), cap(s10), s10)
    // s10: len=6, cap=6, val=[0 1 2 3 4 5]
    fmt.Printf("s11: len=%d, cap=%d, val=%v
", len(s11), cap(s11), s11)
    // s11: len=5, cap=8, val=[2 3 4 5 6]  // cap * 2
    s11 = append(s11, 7, 8, 9, 10)
    fmt.Printf("s11: len=%d, cap=%d, val=%v
", len(s11), cap(s11), s11)
    // s11: len=9, cap=16, val=[2 3 4 5 6 7 8 9 10] // cap * 2

    // 切片拷贝
    s12 := []int{0, 1, 2, 3, 4, 5}
    s13 := s12
    s14 := make([]int, len(s12))
    copy(s14, s12) // 深拷贝
    s12[0] = 100
    fmt.Println(s12) // [100 1 2 3 4 5]
    fmt.Println(s13) // [100 1 2 3 4 5]
    fmt.Println(s14) // [0 1 2 3 4 5]
    s15 := []int{6, 7, 8}
    s12 = append(s12, s15...) // 数组合并
    fmt.Println(s12)          // [100 1 2 3 4 5 6 7 8]
    fmt.Println(s13)          // [100 1 2 3 4 5]

    // 切片删除元素
    s13 = append(s13[:1], s13[2:]...)
    fmt.Println(s13) // [100 2 3 4 5]

    // 注意
    a := make([]int, 5, 10)
    for i := 1; i < 5; i++ {
        a = append(a, i)
    }
    fmt.Println(a) // [0 0 0 0 0 1 2 3 4]

    // 注意
    b := []int{0, 1, 2, 3, 4, 5}
    b1 := b[:]
    b1 = append(b1[:1], b1[2:]...)
    fmt.Println(b1) // [0 2 3 4 5]
    fmt.Println(b)  // [0 2 3 4 5 5]

}
原文地址:https://www.cnblogs.com/luwei0915/p/15357634.html