切片定义

切片是基于数组类型做的一层封装。它非常灵活,可以自动扩容。

var a []int
//定义一个int类型的空切片

切片初始化, a[start:end]创建一个包括从start到end-1的切片。

package main
import ( 
    "fmt"
)
func main() { 
    a := [5]int{76, 77, 78, 79, 80}
    var b []int = a[1:4] //基于数组a创建⼀个切⽚,包括元素a[1] a[2] a[3]
    fmt.Println(b)
}

切片初始化方法2

package main
import ( 
  "fmt"
)
func main() { 
  c := []int{6, 7, 8} //创建⼀个数组并返回⼀个切⽚
  fmt.Println(c)
}

数组切片的基本操作

切片基本操作
a) arr[start:end]:包括start到end-1(包括end-1)之间的所有元素
b) arr[start:]:包括start到arr最后一个元素(包括最后一个元素)之间的所有元素
c) arr[:end]:包括0到end-1(包括end-1)之间的所有元素
d) arr[:]:包括整个数组的所有元素

package main

import (
    "fmt"
)

func testSlice0() {
    var a []int
    if a == nil {
        fmt.Printf("a is nil\n")
    } else {
        fmt.Printf("a = %v\n", a)
    }
    a[0] = 100
}

func testSlice1() {
    a := [5]int{1, 2, 3, 4, 5}
    var b []int
    b = a[1:4]
    fmt.Printf("slice b:%v\n", b)
    fmt.Printf("b[0]=%d\n", b[0])
    fmt.Printf("b[1]=%d\n", b[1])
    fmt.Printf("b[2]=%d\n", b[2])
    fmt.Printf("b[3]=%d\n", b[3])
}

func testSlice2() {
    a := []int{1, 2, 3, 4, 5}

    fmt.Printf("slice a:%v type of a:%T\n", a, a)
}

func testSlice3() {
    a := [5]int{1, 2, 3, 4, 5}
    var b []int
    b = a[1:4]
    fmt.Printf("slice b:%v\n", b)

    // c := a[1:len(a)]
    c := a[1:]
    fmt.Printf("slice c:%v\n", c)
    //d := a[0:3]
    d := a[:3]
    fmt.Printf("slice d:%v\n", d)
    // e  := a[0:len(a)]
    e := a[:]
    fmt.Printf("slice e:%v\n", e)
}

func testSlice4() {
    a := [...]int{1, 2, 3, 4, 5, 7, 8, 9, 11}

    fmt.Printf("array a:%v type of a:%T\n", a, a)
    b := a[2:5]
    fmt.Printf("slice b:%v type of b:%T\n", b, b)
    /*
        b[0] = b[0] + 10
        b[1] = b[1] + 20
        b[2] = b[2] + 30
    */
    /*
        for index, val := range b {
            fmt.Printf("b[%d]=%d\n", index, val)
        }
    */
    for index := range b {
        b[index] = b[index] + 10
    }
    fmt.Printf("after modify slice b, array a:%v type of a:%T\n", a, a)
}

func testSlice5() {
    a := [...]int{1, 2, 3}
    s1 := a[:]
    s2 := a[:]
    s1[0] = 100
    fmt.Printf("a=%v s2=%v\n", a, s2)
    s2[1] = 200
    fmt.Printf("a=%v s1=%v\n", a, s1)
}

func main() {
    //testSlice0()
    //testSlice1()
    //testSlice2()
    //testSlice3()
    //testSlice4()
    testSlice5()
}
test

相关文章:

  • 2022-12-23
  • 2021-10-29
  • 2021-07-22
  • 2021-06-22
  • 2022-12-23
  • 2021-12-06
  • 2022-12-23
猜你喜欢
  • 2022-02-06
  • 2021-06-24
  • 2021-08-30
  • 2021-07-07
  • 2021-11-20
相关资源
相似解决方案