Skip to content

proposal: spec: allow type conversion from generic type to same underlying type #61164

Open
@rogpeppe

Description

@rogpeppe

What version of Go are you using (go version)?

$ go version
go version devel go1.21-f90b4cd655 Fri May 26 03:21:41 2023 +0000 linux/amd64

Does this issue reproduce with the latest release?

Yes

What did you do?

I compiled this code:

type A struct {
	a int
}
type B A

func F[T A | B](x *T) {
	x1 := (*A)(x)
	_ = x1
}

What did you expect to see?

Compilation success. We know that all of the possible types of *T can be converted to *A so the conversion could be OK.

What did you see instead?

./prog.go:9:13: cannot convert x (variable of type *T) to type *A

To work around this, we can use a type switch: https://go.dev/play/p/PfuuWgA4eNG

func F[T A | B](x *T) {
	var x1 *A
	switch x := any(x).(type) {
	case *A:
		x1 = x
	case *B:
		x1 = (*A)(x)
	case *string:
		x1 = nil
	}
	_ = x1
}

But this is considerably more verbose and also more error-prone, because it fail at run time if one of the types in the type set isn't mentioned in the type switch.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions