Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

slice[:1][0] vs slice[0] in go

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’s the logic behind returning &slice[:1][0] instead of &slice[0]? As far as I’m aware (and my tests confirm), both would return the same address. Is there a specific reason that go developers chose to use the former rather than the latter?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

If a slice has positive capacity, you may slice it like slice[:1] which will result in a slice that will have a length of 1, and you may index it like slice[0] without resulting in 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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading