-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Open
Labels
LanguageChangeSuggested changes to the Go languageSuggested changes to the Go languageLanguageChangeReviewDiscussed by language change review committeeDiscussed by language change review committeeProposal
Milestone
Description
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.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
LanguageChangeSuggested changes to the Go languageSuggested changes to the Go languageLanguageChangeReviewDiscussed by language change review committeeDiscussed by language change review committeeProposal