go-切片

64 阅读2分钟

1.定义

切片是一组变长的 数据类型一致的数组

2.创建方式

2.1使用数组

  • var slice1 []type = arr1[start:end]
  • [start:end] 为左闭右开区间,start省略从0开始,end省略则到末尾
  • 存在指向数组元素的指针,切片改变,数组也会相应改变,所以是引用类型
    arr1 := [5]int{1, 2, 3, 4, 5}
    var s1 []int = arr1[1:5]
    fmt.Println(s1) //[2 3 4 5]

    //修改s1的值,arr1也会放生改变,索引是引用类型
    s1[1] = 10
    fmt.Println(s1)   //[2 10 4 5]
    fmt.Println(arr1) //[1 2 10 4 5]
    

    // s2也是通过数组声明 [5]int{1, 4, 3, 2, 6}[:] =>  []int{1, 4, 3, 2, 6}
    s2 := []int{1, 4, 3, 2, 6}

2.2使用make

    s1 := make([]int, 5, 10)
    for k, _ := range s1 {
            s1[k] = k * 2
    }
    fmt.Println(s1)

相关操作

append

  • append(), 用来将元素添加到切片末尾并返回结果
  • 通过数组创建切片,给切片追加元素有两种情形:
    1. 切片长度 小于 数组长度: 引用,同步修改数组元素
    2. 切片长度 大于 数组长度: 重新声明切片,数组元素不发生改变
//append
func append_test() {
	arr1 := [5]int{1, 2, 3, 4, 5}
	tmp_slice_1 := arr1[0:2]

	tmp_slice_1 = append(tmp_slice_1, 5)
	fmt.Println("临时切片1:", tmp_slice_1) //临时切片1: [1 2 5]
	fmt.Println("数组1", arr1)           //数组1 [1 2 5 4 5]
}
func append_test_2() {
	arr1 := [5]int{1, 2, 3, 4, 5}
	tmp_slice_1 := arr1[0:2]

	tmp_slice_1 = append(tmp_slice_1, 5, 6, 7, 8)
	fmt.Println("临时切片1:", tmp_slice_1) //临时切片1: [1 2 5 6 7 8]
	fmt.Println("数组1", arr1)           //数组1 [1 2 3 4 5]
}

copy

  • copy(s1,s2), s1的长度不变,把s1相应索引位置的值 换成s2相应位置索引的值
func copy_test() {
    s1 := make([]int, 5)
    s2 := make([]int, 3)
    s1[1] = 5
    s1[2] = 10
    copy(s2, s1)  //无返回值
    fmt.Println(s2)
}

遍历

    s1 := make([]int, 5, 10)
    for k, _ := range s1 {
            s1[k] = k * 2
    }
    fmt.Println(s1)

长度,容量

  • len()
  • cap()