golang nil slice & empty slice 筆記

示例代碼

package main

import (
    "fmt"
)

func main() {
    a := []string{"A", "B", "C", "D", "E"}
    a = nil
    fmt.Println(a, len(a), cap(a))
}

result: [] 0 0 說明: a 是 一個nil 的slicegolang


package main

import (
    "fmt"
)

func main() {
    a := []string{"A", "B", "C", "D", "E"}
    a = a[:0] //空的slice
    fmt.Println(a, len(a), cap(a))
}

result [] 0 5 說明 a是長度是0的emtpy slice數組

nil slice vs empty slice

  • nil slice 的長度len和容量cap都是0
  • empty slice的長度是0, 容量是由指向底層數組決定
  • empty slice != nil
  • nil slice的pointer 是nil, empty slice的pointer是底層數組的地址

slice的底層表示形式app

[pointer] [length] [capacity]
nil slice:   [nil][0][0]
empty slice: [addr][0][0] // pointer是底層數組的地址

建立nil slice和empty slice

package main

import (
    "fmt"
)

func main() {
    var nilSlice []string
    emptySlice0 := make([]int, 0)
    var emptySlice1 = []string{}

    fmt.Printf("\nNil:%v Len:%d Capacity:%d", nilSlice == nil, len(nilSlice), cap(nilSlice))
    fmt.Printf("\nnil:%v Len:%d Capacity:%d", emptySlice0 == nil, len(emptySlice0), cap(emptySlice0))
    fmt.Printf("\nnil:%v Len:%d Capacity:%d", emptySlice1 == nil, len(emptySlice1), cap(emptySlice1))
}

make slice 規則

package main

import "fmt"

func main() {
  s1 := make([]int, 5)
  fmt.Printf("The length of s1: %d\n", len(s1))
  fmt.Printf("The capacity of s1: %d\n", cap(s1))
  fmt.Printf("The value of s1: %d\n", s1)
  s2 := make([]int, 5, 8)
  fmt.Printf("The length of s2: %d\n", len(s2))
  fmt.Printf("The capacity of s2: %d\n", cap(s2))
  fmt.Printf("The value of s2: %d\n", s2)
}

make 初始化slice函數

  • 第一個參數表示長度
  • 第二個參數表示容量
  • make函數初始化切片時,若是不指明其容量,那麼它就會和長度一致

links

相關文章
相關標籤/搜索