zlacker

[return to "Go(lang): Robust generic functions on slices"]
1. TheDon+IZ2[view] [source] 2024-02-24 05:22:50
>>signa1+(OP)
The problems with the API they point out are almost all things that rust's ownership system was built to solve.

Things like:

    slices.Sort(s) // correct
    slices.Compact(s) // incorrect
    slices.Delete(s, ...) // incorrect
    s := slices.Delete(s, ...) // incorrect if 's' is referenced again in the outer scope
    s = slices.Delete(s, ...) // correct
All of those are solved by having functions like 'slices.Sort' take a '&mut' reference in rust speak, and having 'slices.Compact' and 'Delete' take an owned slice, and return a new owned slice.
◧◩
2. shakow+Qj3[view] [source] 2024-02-24 10:35:42
>>TheDon+IZ2
IMHO, all these comes from the million dollar mistake that Go made from the very beginning, with slices being a bastard between both an owned and non-owned data container. Indeed, any function accepting a slice may simply use it as an immutable view on whatever data it needs, or modify it, potentially re-alloc it, and wreak havoc by invalidating all previous references to it and/or its elements. And God forbid you passed a subslice to such a function, you're in for a nasty surprise.

Even without going the whole 9 yards of the Rust memory model, something like the views in C++, or the java {Array,Linked}Lists containing references to objects and thus being resistant to re-alloc, or even plainly immutable list like in OCaml are all working and simple enough solutions to the issue.

I still can't wrap my mind around how supposedly experienced people like Pike & co. may have designed slices, then went ‶yep, that makes perfect sense for a robust, basic, widely used data structure to create our language around″, outside of a few toy programs.

◧◩◪
3. bsaul+Oe4[view] [source] 2024-02-24 18:53:34
>>shakow+Qj3
my feeling with slices is that go wanted to really make programmers mindful of the cost of allocating new space on array operations.

By having this weird API on slices, they force you to be explicit on allocating new memory.

◧◩◪◨
4. maskli+ti4[view] [source] 2024-02-24 19:18:53
>>bsaul+Oe4
None of that makes any sense. Slices don't force you to be explicit on allocating new memory in any way. you can literally do this:

    s := []int{}
    for i := range 29754 {
        s = append(s, i)
    }
do you see explicit allocation of new memory? As far as I'm concerned that's not in any way more explicit than e.g.

    var s = new List();
    foreach(var i in Enumerable.Range(0, 29754)) {
        s.Add(i);
    }
◧◩◪◨⬒
5. bsaul+4j4[view] [source] 2024-02-24 19:23:06
>>maskli+ti4
s = append(s,i) makes you realize something happened to the memory behind s. Otherwise you would simply call s.append(i)
[go to top]