GO语言学习——切片二

使用make()函数构造切片

格式:

make([]T, size, cap)

其中:

  • T:切片的元素类型
  • size:切片中元素的数量
  • cap:切片的容量

切片的本质

切片的本质就是对底层数组的封装,它包含了三个信息:

  • 底层数组的指针
  • 切片的长度(len)
  • 切片的容量(cap)

切片的本质

切片就是一个框,框住了一块连续的内存。

切片属于引用类型,真正的数据都是保存在底层数组里的。

判断切片是否为空

使用len(s) == 0来判断

切片不能直接比较

  • 一个nil值的切片没有底层数组

  • 一个nil值的切片的长度和容量都是0

  • 一个长度和容量都是0的切片不一定是nil

切片的赋值拷贝

切片遍历

  • 索引遍历和

  • for range遍历

    package main

    import "fmt"

    // make()函数创造切片

    func main(){

    s1 := make([]int,5,10)

    fmt.Printf("s1=%v len(s1)=%d cap(s1)=%d\n", s1, len(s1), cap(s1)) // s1=[0 0 0 0 0] len(s1)=5 cap(s1)=10

      s2 := make([]int,0,10)
      fmt.Printf("s2=%v len(s2)=%d cap(s2)=%d\n", s2, len(s2), cap(s2)) // s2=[] len(s2)=0 cap(s2)=10
    
      // 切片的赋值
      s3 := []int{1,3,5}
      s4 := s3 // s3和s4都指向了同一个底层数组
      fmt.Println(s3, s4)
      s3[0] = 1000
      fmt.Println(s3, s4)
    
      // 切片的遍历
      // 1. 索引遍历
      for i:=0;i<len(s3);i++ {
            fmt.Println(s3[i])
      }
      // 2. for range循环
      for i,v := range s3 {
            fmt.Println(i, v)
      }
    

    }

vscode 配置代码片段

Ctrl + Shift + P snippets go(go.json)

{
        // Place your snippets for go here. Each snippet is defined under a snippet name and has a prefix, body and 
        // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
        // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
        // same ids are connected.
        // Example:
        // "Print to console": {
        //      "prefix": "log",
        //      "body": [
        //              "console.log('$1');",
        //              "$2"
        //      ],
        //      "description": "Log output to console"
        // }
        "println":{
                "prefix": "pln",
                "body":"fmt.Println($0)",
                "description": "println"
        },
        "printf":{
                "prefix": "plf",
                "body": "fmt.Printf(\"$0\")",
                "description": "printf"
        }
}