On Wed, Oct 7, 2020 at 9:12 PM Howard C. Shaw III <howardcs...@gmail.com>
wrote:

> You said:
>
>> I was trying around with arrays and generics because slices are more
>> complex to reason about than arrays. For example, I introduced bugs into my
>> code by not being fully aware of slices overwriting original data when you
>> append to them and the capacity is not set correctly. So, when writing
>> critical code it could be safer to avoid slices if possible for
>> this reason. Another example:
>>
>
> In my experience, you either have a fixed array size in mind to begin with
> (as in a fixed array size in a struct for padding or matching a fixed size
> C array) or you should be using a slice anyway.
>
> The trouble mostly comes when you keep the array around after making a
> slice of it. If you are  going to be doing *any* manipulation of a slice,
> abandoning the underlying array and only carrying around slices gets rid of
> most such errors. A slice already IS effectively an 'array, generic on
> size.'
>

Hm, abandoning the underlying array does not really help I think:

u := []byte{0, 1, 2, 3}
a := u[0:2]
b := u[2:]
u = nil  // abandon u
a = append(a, 4)
fmt.Println(b) // [4, 3]!! not intended

Should be:

u := []byte{0, 1, 2, 3}
a := u[0:2:2] // use correct capacity!
b := u[2:len(u)] // use correct capacity!
u = nil // abandon u
a = append(a, 4)
fmt.Println(b) // [2, 3], ok!

Btw, I am not saying fixed arrays are a solution for this of course and I
agree it is not a big problem in practice as otherwise slices are really
handy.




-- 
> You received this message because you are subscribed to a topic in the
> Google Groups "golang-nuts" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/golang-nuts/MF1UzRrx9mU/unsubscribe.
> To unsubscribe from this group and all its topics, 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/08fe15f5-dff1-4651-b824-86266b3ce50bn%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/08fe15f5-dff1-4651-b824-86266b3ce50bn%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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/CAMoB8rU4imEf5OdRi_0DXpH6y21r5kcw6UzXUPCz%3DQqpuwC3Hw%40mail.gmail.com.

Reply via email to