3 ms·
The "solution" is to accept an `interface{}` and pass in a `[]struct`! "When writing generic Go, only accept `interface{}` and never a slice" is a painful maxi
by cjslep 7y ago
The "solution" is to accept an `interface{}` and pass in a `[]struct`!
"When writing generic Go, only accept `interface{}` and never a slice" is a painful maxim but works.
- tsimionescu 7y agoWell, that would allow you to call the function, but now you can't write the body of the function without reflection: you can't iterate over an interface{}, and you can't cast a []struct (edit) wrapped in an interface{} (/edit) to a []SomeInterface, so you're back to square one.
- cjslep 7y agoYes, but now you no longer need to change the function declaration and all callsites (major version change) to support new types (if they're slices or not), just need to implement more reflection or typecasting cases within the function (minor version change).
- tsimionescu 7y agoCounterpoint: if you modify the call site to pass in a new value, you don't know whether the function will accept it or not, since you've opted out of any compiler verification.
- cjslep 7y agoThat's a very weak argument since you're already opting out of every other kind of compiler check by using `interface{}` as an element type to begin with. Yet another reason to just use `interface{}`: if the caller already has a value of type `[]Concrete` then they can just pass it in directly; otherwise the caller will need to allocate and copy the value's elements into a new value of `[]interface{}` type since the `[]Concrete` is not castable: https://play.golang.org/p/whh1mAAlN-N https://play.golang.org/p/whh1mAAlN-N
- tsimionescu 7y agoMy point was that it is a bad idea to write functions that take an interface{} and try to reflect on it, since you are putting out of all compiler checks. You also get a much, much slower function.
- GenericsMotors 7y agoThe other much less painful maxim is to take a pass on Go, and use a language that's not stuck in the early 70s and with a rabid fanbase to boot.