On Thu, Jul 27, 2023 at 3:17 PM 'Michael Knyszek' via golang-nuts
<golang-nuts@googlegroups.com> wrote:
>
> The number 32 for the capacity comes from this constant, and the returned 
> byte slice in that case is likely coming from a compiler-inserted call to 
> stringtoslicebyte. An empty string is correctly replaced by a zero-length 
> byte slice, it just so happens that the capacity of the array backing that 
> slice may or may not be zero. As Brian said, commenting or uncommenting that 
> line likely just leads to the byte slice's backing array being allocated 
> differently.
>
> I believe this is working as intended, because I don't think the spec makes 
> any guarantees about the capacity of the slice you get back from a 
> conversion. On the one hand, it is a little surprising given that the make 
> builtin very explicitly sets the capacity of the slice. On the other hand, 
> append is an example of a built-in that may return a slice with a larger 
> capacity than requested, so it's not like this case is the only outlier.

I agree that this is not a bug.  The language makes no promises about
the capacity of the slice returned by a string to []byte conversion.

The comment in the code

//this crashes, panics because capacity is 0, even though I can access
all 32 bytes in the loop above

is misleading.  In the case that crashes, the program can't access all
32 bytes in the loop above.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcWV%3D-g9m8A_EhLnTyuK0x2ffkgDP5wCJtPKG%3DWkM77FUg%40mail.gmail.com.

Reply via email to