You don’t even know the difference between a nil slice and an empty slice? The BAT interviewer will have to send you home to wait for the announcement.
The problem
package main
import (
"fmt"
"reflect"
"unsafe" ) func main(a) { 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) } Copy the code
Do nil slices point to the same address as empty slices? What does this code output?
How to answer
- Nil slices and empty slices point to different addresses. Nil Null slice reference array pointer address is 0 (does not point to any real address)
- The null slice reference array pointer address is present and 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 slices and empty slices point to different array addressestrue// Both empty slices point to the same array address, 824634207952Copy the code
explain
- As mentioned in previous articles, the data structure of slicing is
type SliceHeader struct {
Data uintptr // Reference the array pointer address
Len int // The current length of the slice
Cap int // The capacity of slices
}
Copy the code
-
The big difference between nil slices and empty slices is thatThe array reference addresses pointed to are different.
-
All empty slices point to the same array reference address
Article recommendation:
- Is yesterday’s colleague from the append element in the for loop still around today?
- Golang interviewer: What happens if the channel is already closed for select? What if there’s only one case?
- Golang interviewer: What happens if the channel is already closed for select? What if there’s only one case?
- Golang Interview question: What would it be like to read and write the chan that has been turned off? Why is that?
- Golang interview question: What about reading and writing uninitialized Chan? Why is that?
- Golang interview question: How do reflect get field tag? Why can’t json packages export tags for private variables?
- Golang: What happens to json package variables without tags?
- Golang interview question: How to avoid memory escape?
- Golang interview question: What about memory escape?
- Golang: Does memory copy happen when a string is converted into a byte array?
- Golang Interview question: Flip the string containing Chinese characters, numbers, and English letters
- Golang: Is it necessarily more expensive to copy a large slice than a small one?
- Golang: What’s the difference between uintptr and unsafe.Pointer?