It's common practice to *write* to elements between the length and capacity 
of a slice.  Usually, you use append to do that.
It's bad practice to *read* elements between the length and capacity. Which 
you can't do with a simple indexing op, of course. You would have to 
reslice larger and then index.
In that sense, it would be nice to have the GC not trace elements between 
len and cap. They should be dead if you never read them, only write them. 
It's hard to do in the GC, it requires a language change, etc. But it would 
be nice.


On Thursday, March 26, 2020 at 12:29:04 PM UTC-7 leszek...@gmail.com wrote:

>
>
>
>> I disagree. I do that all the time. It's also how `append` was 
>> implemented before it existed as a predeclared function. It's also, FWIW, 
>> used in bytes.Buffer <https://golang.org/src/bytes/buffer.go#L107>. I 
>> agree that unless your API is very clear about it, you shouldn't really 
>> access a slice past the length for one of your arguments. But there *are* 
>> APIs where it's clear that's happening (e.g. anything having "append" in 
>> it's doc-string) and there are use-cases where you control the slice for 
>> its entire lifetime and where it can make code more readable.
>>
>
>  I didn't even know that append wasn't there, but since we have it isn't 
> it meant to be used in the first place?
> Of course if we check the capacity, expanding past len is safe, like 
> s[:cap(s)]. I would check the capacity only in case when I really don't 
> want to end with a new slice buffer as a result of appending more than the 
> available space.
>

-- 
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/aeb6767a-0807-462a-a2d5-0b066299a5d0%40googlegroups.com.

Reply via email to