3 ms·
With the introduction of generics in Go 1.18 and the accompanying "slices" package (https://github.com/golang/go/issues/45955 https://github.com/golang/go/issue
by benhoyt 5y ago
With the introduction of generics in Go 1.18 and the accompanying "slices" package (https://github.com/golang/go/issues/45955 https://github.com/golang/go/issues/45955), we might soon write that as:
a = slices.Delete(a, i, i+1)
That said, in code I write, I rarely need to do an in-place delete from a slice. I think it's rare enough that recognizing the idiom is okay.
- azth 5y agoIt's so weird why they're adding a slices package instead of making them functions on the slice itself. They did the same with strings. Compare strings.ToUpper(strings.Replace(strings.Trim(s), "a", "b"))) Instead of s.Trim().Replace("a, "b").ToUpper()
- benhoyt 5y agoFor better or worse, this is by design. See: https://golang.org/doc/faq#methods_on_basics https://golang.org/doc/faq#methods_on_basics It's "to avoid complicating questions about the interface (in the Go type sense) of basic types". It also allows separating the builtin functions, of which there are very few (they have to be in the core language spec), from the stdlib functions like strings.ToUpper, which there are many many more of and are added to more quickly than the builtins.
- azth 5y agoI'm not sure what their answer means. They used a similar hand wavy answer about why the language has null pointers. "Complication" here refers to how complicated their implementation of the compiler is, not the end user complication, which is what they traded off (simpler compiler for more complex user code). I didn't get the last point. builtin functions are there (for a big part) because the language doesn't have generics. Functions on types can be added without affecting the interface, since strings don't implement any interface (at least not on purpose, another problem with golang). Java constantly enriches standard library types with more useful methods.
- lanstin 5y agoBecause in-place delete is slow and you want to avoid algorithms with a lot of in-place deletes. So it's ok to have it be awkard, it's like the names of rare elements being longer than the names of common elements, not an issue.