Don’t you even know the difference between nil slices and empty slices? Then the BAT interviewer will have to ask you to go back and wait for the notification.

Insert image description here
Don’t you even know the difference between nil slices and empty slices? Then the BAT interviewer will have to ask you to go back and wait for the notification.
question

package main

import (
 "fmt"
 "reflect"
 "unsafe"
)

func main() {
    
    

 var s1 []int
 s2 := make([]int,0)
 s4 := make([]int,0)
 
 fmt.Printf("s1 pointer:%+v, s2 pointer:%+v, s4 pointer:%+v, \n", *(*reflect.SliceHeader)(unsafe.Pointer(&s1)),*(*reflect.SliceHeader)(unsafe.Pointer(&s2)),*(*reflect.SliceHeader)(unsafe.Pointer(&s4)))
 fmt.Printf("%v\n", (*(*reflect.SliceHeader)(unsafe.Pointer(&s1))).Data==(*(*reflect.SliceHeader)(unsafe.Pointer(&s2))).Data)
 fmt.Printf("%v\n", (*(*reflect.SliceHeader)(unsafe.Pointer(&s2))).Data==(*(*reflect.SliceHeader)(unsafe.Pointer(&s4))).Data)
}

Do nil slices and empty slices point to the same address? What will this code output?

How to answer

nil slices and empty slices point to different addresses. The nil empty slice reference array pointer address is 0 (it does not point to any actual address). The
reference array pointer address of the empty slice exists and is fixed to a value.

s1 pointer:{
    
    Data:0 Len:0 Cap:0}, s2 pointer:{
    
    Data:824634207952 Len:0 Cap:0}, s4 pointer:{
    
    Data:824634207952 Len:0 Cap:0}, 
false //nil切片和空切片指向的数组地址不一样
true  //两个空切片指向的数组地址是一样的,都是824634207952

explain

  • I mentioned in the previous article that the data structure of slices is
type SliceHeader struct {
    
    
 Data uintptr  //引用数组指针地址
 Len  int     // 切片的目前使用长度
 Cap  int     // 切片的容量
}
  • The biggest difference between nil slices and empty slices is that the array reference addresses they point to are different.
    Insert image description here
  • All empty slices point to the same array reference address.
    Insert image description here

Guess you like

Origin blog.csdn.net/m0_73728511/article/details/132866300