切片是对数组的引用,对切片的改变会改变原数组的值

package main

import "fmt"

func test6(){
    arr:=[...]int{0,1,2,3,4,5,6,7,8,9,10}
    s1:=arr[2:6]
    fmt.Println(arr)
    fmt.Println(s1)
    s1[0]=200
    fmt.Println(arr)
    fmt.Println(s1)
}

func main() {
    test6()
}

//结果
[0 1 2 3 4 5 6 7 8 9 10]
[2 3 4 5]
[0 1 200 3 4 5 6 7 8 9 10]
[200 3 4 5]

slice的扩展:只能向后扩展,不能向前扩展

s[i]不可以超越len(s),向后扩展不能超越底层数组cap(s)

package main

import "fmt"

func test(){
    arr:=[...]int{0,1,2,3,4,5,6,7,8,9,10}
    s1:=arr[2:6]
    s2:=s1[3:5] 
    fmt.Println(arr)
    fmt.Println(s1)
    fmt.Println(s2) 
}

func main() {
    test()
}

//结果

[0 1 2 3 4 5 6 7 8 9 10]
[2 3 4 5]
[5 6]


相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-10
  • 2022-02-22
猜你喜欢
  • 2022-12-23
  • 2021-07-18
  • 2021-11-11
  • 2022-12-23
  • 2022-12-23
  • 2021-12-26
相关资源
相似解决方案