The following program fails:
func Equal(type T comparable)(x, y T) bool {
return x == y
}
func main() {
var x interface{} = 5
var y = 5
fmt.Println(Equal(x, y))
}
The error is:
prog.go2:15:23: type int of y does not match inferred type interface{} for T
Although it's true that the types don't match exactly, it seems to me that it might be nice
to allow the type argument to unify to interface{} in the same way that we allow
a concrete type to be passed to an interface type.
hi @rogpeppe
i am with you and if with a 'comparable', it would be nice to even have it in basic types...
this:
func main() {
var x interface{} = 5
var y = 6.1
fmt.Println(Equal(x, interface{}(y)))
}
should also work for:
func main() {
var x = 5
var y = 6.1
fmt.Println(Equal(x, y))
}
I am very concerned about avoiding any possible confusion in which type inference does not act as people expect. This is based on the complexity of the C++ equivalent to type inference, which observably confuses people. I would rather say that if there is any confusion, the programmer must explicitly state the desired type.
I too would like to see better type inference here, but I think this is the sort of refinement that can (and should!) wait until after the initial implementation and release of generics, so that we can gather empirical evidence to weigh the cost (of more difficulty reasoning about inference) against the benefit (of avoiding the verbosity and distraction of “obvious” annotations).
Most helpful comment
I too would like to see better type inference here, but I think this is the sort of refinement that can (and should!) wait until after the initial implementation and release of generics, so that we can gather empirical evidence to weigh the cost (of more difficulty reasoning about inference) against the benefit (of avoiding the verbosity and distraction of “obvious” annotations).