Skip to content

generics: Inconsistent ability to access struct fields in functions with type parameter of struct underlying types #51977

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
augustoroman opened this issue Mar 27, 2022 · 1 comment

Comments

@augustoroman
Copy link
Contributor

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

1.18 on playground and gotip on playground

Does this issue reproduce with the latest release?

Yes

What did you do?

I can access the fields of structs when the underlying type is a slice of structs:

type I interface{ ~[]struct{ A, b int } }
func Print[T I](v T) {
	fmt.Println(v[0].A) // ✅ Works
}

...but not if the underlying type is just a struct:

type I interface{ ~struct{ A, b int } }
func Print[T I](v T) {
	fmt.Println(v.A) // ❌ Doesn't work
}

https://go.dev/play/p/NbD6d99neQN
https://go.dev/play/p/NbD6d99neQN?v=gotip

What did you expect to see?

Program should run.

What did you see instead?

./prog.go:12:16: v.A undefined (type T has no field or method A)

Go build failed.
@ianlancetaylor
Copy link
Contributor

In the case that works, every valid type argument will be a slice of the exact type struct{ A, b int }. Since there is only one possible type there, the compiler permits the field access.

In the case that fails, there are an infinite number of types. It's true that all of those types will have a field A. But as it says in the release notes:

The Go compiler does not support accessing a struct field x.f where x is of type parameter type even if all types in the type parameter's type set have a field f. We may remove this restriction in a future release.

Closing because this is working as expected. Making this case work is #48522.

@golang golang locked and limited conversation to collaborators Mar 27, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants