Slicing vs. slicing in Go

王林
Release: 2024-02-05 23:42:03
forward
404 people have browsed it

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].

Copy after login

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])
Copy after login

This results in:

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

But this works:

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template