4 ms·
This one of my top Go complaints as well (and I love the language). If Foo implements interface Bar (Baz() error, Moo() string), then I should be able to pass
by pstuart 7y ago
This one of my top Go complaints as well (and I love the language).
If Foo implements interface Bar (Baz() error, Moo() string), then I should be able to pass in []Foo to an argument expecting []Bar, because the former is a slice of a type Bar. The compiler should be a good compiler and do the needful to manage args.
All I can expect do on the called side is iterate through the slice, and call the interface function on each element. That sounds contractual to me :-).
- tsimionescu 7y agoAs I explained, that is wrong. You would need a different type, let's call it read-only-slice,to support that. To make the problem more explicit, let's say you have func baz(bars []Bar) { bars[0] = nil } type Foo struct {} baz(make([]Foo, 5)) In this case, the program would fail at runtime, as you can't store a nil in a slice of Foos. The baz() function is perfectly correct in itself, if you passed an array of Bars it would work perfectly.
- pstuart 7y agoI get that part. I want the language/compiler to allow me to use it where it makes sense (as an argument) and prohibit doing things to it that don't (as you demonstrated).
- tsimionescu 7y agoThat would be nice in principle, but where do you expect the error to be thrown in the example above? I don't know of any language which tries to automatically deduce whether a variable is used in a read-only manner or not, and base covariance on this deduction. Even C++, which allows you to explicitly annotate an array to declare that it is read-only (const vector<base*> ) doesn't allow you to pass an array of derived elements instead, so I assume there is some difficulty in implementing these checks and ensuring correctness.