Compilation Error with Generics: Constraining a Type Parameter to a Struct with a Specific Field in Go

Hello everyone,

I’ve ran into a compilation issue that I’m hoping to get some help with. Here’s a simplified code snippet that’s causing trouble:

func mult[T ~struct{ X int }](s T) {
	// Error is here: Unresolved reference 'X'
	fmt.Println(s.X * s.X)
}

type S struct {
    X int
}

func main() {
    mult(S{})
}

I intended for the mult function to accept any type U that has a struct with a field X. The S struct should satisfy this constraint, but I’m getting a compilation error at s.X, saying: “Unresolved reference ‘X’”.

Here is a link to the code on the playground: Go Playground - The Go Programming Language

Could anyone point out what I might be doing wrong?
Thank you in advance for your assistance!

Hello there. Go generics type constraints do not support access to struct fields. You can check a lot of discussions and proposals for this change on golang GitHub e.g., this one.

1 Like