Home  >  Article  >  Backend Development  >  Slicing vs. slicing in Go

Slicing vs. slicing in Go

王林
王林forward
2024-02-05 23:42:03400browse

Slicing vs. slicing in Go

Question content

In the documentation of the unsafe.SliceData function in go, it says:

SliceData returns a pointer to the underlying array of the argument
slice.

If cap(slice) > 0, SliceData returns &slice[:1][0].

What is the logic behind returning &slice[:1][0] instead of &slice[0]? As far as I know (and my testing confirms), both return the same address. Is there any specific reason why Go developers choose to use the former rather than the latter?


Correct answer


A slice may have positive capacity (cap(slice) > 0), but at the same time it may have 0 length. Indexing it like slice[0] will cause a runtime panic.

If the slice has positive capacity, you can slice it like slice[:1], which will produce a slice of length 1, and you can slice it like result[0] That way the results are indexed without causing a runtime panic.

For example:

slice := make([]int, 0, 5)
fmt.Println(&slice[0])

This results in:

panic: runtime error: index out of range [0] with length 0

But this works:

fmt.Println(&slice[:1][0])

The above is the detailed content of Slicing vs. slicing in Go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete