19

golang nil slice & empty slice 笔记

 4 years ago
source link: https://studygolang.com/articles/29136
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

示例代码

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 的slice

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的底层表示形式

[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

欢迎关注我们的微信公众号,每天学习Go知识

FveQFjN.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK