Go version
go version go1.22.4 darwin/arm64
Output of go env
in your module/workspace:
Doesn't matter.
What did you do?
Go's generics supports defining constraints on array sizes:
type commonBinaryLengths interface {
// footgun | address | hash | pubkey
~[]byte | ~[20]byte | ~[32]byte | [48]byte
}
However, creating constraints out of those in another dimension fails to infer:
type commonArrayLengths[U commonBinaryLengths] interface {
// footgun | roots
~[]U | ~[8192]U
}
Explicitly spoon feeding the compiler with the types will succeed in building the code, so it seems it's not a misuse of generics, simply a bug in the compiler's inference system:
https://go.dev/play/p/DdmLfxH5eaq
What did you see happen?
The inferred generic calls fail to compile whereas the spoon-fed ones build fine.
What did you expect to see?
I expect all lines to compile and run successfully.
Comment From: gabyhelp
Related Issues
- Incorrect generic type inference #64734 (closed)
- spec: function type inference ignores type parameter constraints #50272 (closed)
- cmd/compile: type inference fails on a case which looks simple #63750 (closed)
- cmd/compile: Generics not properly working when been used with unsafe casts #51042 (closed)
- spec: interfaces that have different-size method sets never unify (but they possibly could) #57192 (closed)
- cmd/compile: cannot index pointer to generic array #49447 (closed)
- cmd/compile/internal/types2: review implementation of indexing of generic types #49275 (closed)
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
Comment From: thanm
@golang/compiler
Comment From: timothy-king
commonArrayLengths
does not have a core type. So type inference does not proceed to unify T
with [][32]byte
. So U
is not inferred to be [32]byte
. This is the observed error message. So this is not a bug. It is possible this could be supported in the future, but it is not supported at the moment.
Fixing this requires a change to the unification algorithm to proceed in some cases without a core type. I suspect this requires a proposal too.
https://github.com/golang/go/issues/63750#issuecomment-1781383214 applies. Closing.