Skip to content

proposal: spec: support type inference on generic structs #61731

Open
@matthewmueller

Description

@matthewmueller

(I couldn't find an existing issue for this, but if there is, feel free to close!)

Problem

There's some inconsistencies in the capabilities of type inference for generics.

With functions, type inference works beautifully:

func Accepts[In, Out any](json func(in In) (Out, error), html func(in In) error) http.Handler {
  // call appropriate function depending on Accepts header
}

type Input struct {}
type Output struct {}

func indexJson(in *Input) (Output, error) {
  // render json
}

func indexHtml(in *Input) error {
  // render html
}

// Usage
router.Get("/", Accepts(indexJson, indexHtml))

Structs also work, but they require you to explicitly pass in the generic types:

type Accepts[In, Out any] struct {
  JSON func(in In) (Out, error)
  HTML func(in In) error
}

func (a *Accepts) ServeHTTP(w, r) {
}

// Usage
router.Get("/", Accepts[*Input, Output]{indexJson, indexHtml})

It feels rather unfortunate that you need to explicitly set the [*Input, Output] when usage and even syntax is otherwise so similar.

Proposal

Support type inference on structs, allowing the following:

router.Get("/", Accepts{indexJson, indexHtml})

When the concrete types in indexJson and indexHtml don't line up, it's a type error.


Thanks for your consideration!

Metadata

Metadata

Assignees

No one assigned

    Labels

    ProposalTypeInferenceIssue is related to generic type inferencegenericsIssue is related to generics

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions