Skip to content

cmd/compile: generics cannot infer slice/array of slice/array types #68262

Closed

Description

@karalabe

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.

Activity

  1. thanm commented on Jul 1, 2024

    @thanm
    Contributor

    @golang/compiler

  2. added
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Jul 1, 2024
  3. changed the title [-]cmd/compiler: generics cannot infer slice/array of slice/array types[/-] [+]cmd/compile: generics cannot infer slice/array of slice/array types[/+] on Jul 1, 2024
  4. timothy-king commented on Jul 2, 2024

    @timothy-king
    Contributor

    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.

    #63750 (comment) applies. Closing.

  5. locked and limited conversation to collaborators on Jul 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.compiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions