Skip to content

cmd/compile: investigate relaxation of mono-checker restrictions for generic methods #81699

Description

@griesemer

[This is a spin-off from #80109, inspired by a comment from @jswright.]

Code such as

type T[P any] struct{}

func (T[P]) m() T[T[P]] {
	panic("unimplemented")
}

is not accepted by the compiler because an instantiation of T with a type X would lead to the instantiation of T with T[X] and then with T[T[X]] and so forth because when T[X] is instantiated, the method m is created, which produces (returns) the type T[T[X]] and with that all that type's methods must be created. The monomorphization checker prevents such infinite expansion by reporting an error (playground). The immediate creation of all the methods for an instantiated type is needed because the type may be used with an interface, possibly in another package, unbeknownst to the compiler, and then all methods must be present.

However, if m is written as a top-level generic function (rather than a method)

func m[P any](T[P]) T[T[P]] {
	panic("unimplemented")
}

the problem disappears because T[T[X]] doesn't imply the instantiation of another function (taking that argument) unless that function is called.

The Go 1.27 release introduced generic methods. Generic methods cannot be used to satisfy interface methods (there is currently no way to declare a generic interface method). Thus, such generic methods could be modeled/implemented by the compiler as generic functions (which don't have the mono-checker restriction).

Thus it may be possible to remove the mono-checker restriction for generic methods.

Activity

  1. added this to the Backlog milestone on Sep 23, 2026
  2. added
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Sep 23, 2026
  3. mrkfrmn commented on Sep 23, 2026

    @mrkfrmn
    Contributor

    Let's also link #80172, but the gist was (to me):

    Suppose there is a method I'd like to have:

    func (s S[E]) chunk() S[S[E]] { ... } // ERROR: cannot monomorphize 
    

    I could imagine users declaring unused type parameters to "opt out" of dynamic dispatch:

    func (s S[E]) chunk[_ any]() S[S[E]] { ... }
    

    And this type argument introduces burden for callers.

    It seems there should be some other way to constrain the method to static use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

NeedsInvestigationSomeone 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.

Projects

Relationships

None yet

Development

No branches or pull requests

Issue actions