Comment by omeid2
1 year ago
Without defending this API, the easiest way to go about avoiding bugs when working with slice mutating functions is to consider all those "fine" scenarios as not fine.
Always assume that only the return value of slice mutating functions are the valid reference and the old one always invalid. This is not always completely accurate, but it is very useful in that, it is also never "wrong".
> Without defending this API, the easiest way to go about avoiding bugs when working with slice mutating functions is to consider all those "fine" scenarios as not fine. Always assume that only the return value of slice mutating functions are the valid reference and the old one always invalid.
The first "fine" scenario is fine because `slices.Sort` works in place, it doesn't return a value at all.
And the other "fine" versions do essentially what you advocate, by overwriting the invalid reference with the new one.
The nil return assignment is a compile time error, so easy to spot. It is not supposed to be the defence of the API or a silver bullet, just a practical rule that can save you some hustle.
By returning nil, the function makes it clear that it doesn't move the input reference
Yes, but now I have to keep track of which functions invalidate-and-return and which return nil. If I forget that `slices.Delete` returns a new slice instead of mutating in-place, the language doesn’t help me.