Constrain a type parameter to be assignable to another

265 views
Skip to first unread message

Michael Andersen

unread,
Mar 17, 2022, 12:44:08 AM3/17/22
to golang-nuts
Hi

Is there a way to constrain one parameter to be assignable to another?

For example, in ye olde days, I'd have:

type Iface interface {
// ...
}

type Concrete1 struct { /* ... */ }
var _ Iface = &Concrete1{}

type Concrete2 struct{ /* ... */ }
var _ Iface = &Concrete2{}

// Repeat ad nauseam


Now, I'm finding myself wanting similar compile time checks for generic types and functions. E.g.

func foo[Iface any, Concrete Iface]() {
  var c Concrete
  var _ Iface = c
}


Obviously that's a bit contrived, but I'm writing code that needs both the concrete type (*someStruct) and the interface it's meant to adhere to.

The above code does not compile with 1.18 (cannot use a type parameter as constraint)

I have a runtime check that works, but I'd love a compile time check. Is there a way to do that?

Thanks
Michael



Axel Wagner

unread,
Mar 17, 2022, 2:02:39 AM3/17/22
to Michael Andersen, golang-nuts
No, it's not possible. If there is a compelling enough use-case, it might be made possible in the future (though not sure, how), but as it stands, it isn't.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/c78b9b90-a5e2-4acd-8026-a126805cb643n%40googlegroups.com.

Ian Lance Taylor

unread,
Mar 17, 2022, 9:49:42 PM3/17/22
to Michael Andersen, golang-nuts
On Wed, Mar 16, 2022 at 9:44 PM Michael Andersen <mic...@steelcode.com> wrote:
>
> Is there a way to constrain one parameter to be assignable to another?

Currently there is not. We're not sure how to handle that case. See
https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md#no-way-to-express-convertibility
.

Ian
Reply all
Reply to author
Forward
0 new messages