2 ms·
As 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
by tsimionescu 7y ago
As 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.