Go version
1.24.3
Output of go env
in your module/workspace:
any environment
What did you do?
import (
"fmt"
"iter"
"slices"
)
func PrintSeq[S iter.Seq[E], E any](seq S) {
for s := range seq {
fmt.Println(s)
}
}
func PrintSlice[S []E, E any](seq S) {
for _, s := range seq {
fmt.Println(s)
}
}
type Seq[E any] interface {
[]E | iter.Seq[E]
}
func Print[S Seq[E], E any](seq S) {
var s iter.Seq[E]
switch v := any(seq).(type) {
case iter.Seq[E]:
s = v
default:
if v, ok := v.([]E); ok {
s = slices.Values(v)
}
}
for e := range s {
fmt.Println(e)
}
}
func main() {
s := []string{"a", "b", "c"}
PrintSeq(slices.Values(s)) // a b c
PrintSlice(s) // a b c
Print(s) // in call to Print, cannot infer E
}
But with
type Seq[E any] interface {
[]E
}
it works.
What did you see happen?
This is clearly a compiler issue with generics constraints and iter.Seq. In fact, there are three identical calls but in the latter case the compiler cannot infer about type. The same applies to iter.Seq2.
What did you expect to see?
There must be identical type inference at compile time.
Comment From: gabyhelp
Related Issues
- spec: function type inference ignores type parameter constraints #50272 (closed)
- cmd/compile: spurious "cannot infer T" type error #66842 (closed)
- proposal: spec: infer types from sufficiently constrained constraints #73527
- Incorrect generic type inference #64734 (closed)
- cmd/compile: generics cannot infer slice/array of slice/array types #68262 (closed)
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
Comment From: mknyszek
CC @mrkfrmn
Comment From: mknyszek
CC @griesemer
Comment From: mwriter
@mknyszek I think I'm too late :) https://github.com/golang/go/issues/73527 I guess I should close the issue and wait for better times ;)
Comment From: mrkfrmn
Ahh, thanks for the added context. Given Robert's comments there, I think it's wise to wait as you mentioned.