Which operations can you perform on a value of type parameter type? Why can't you access a struct field even when every type in the set has it?
Question 118HardGo 1.22 to 1.25
An operation is allowed on a value of type T only if it is valid for every type in T's type set, and the spec explicitly permits it:
- Operators (
+,<,==) work if every type in the set supports them. - Methods can be called only if they are listed in the constraint.
- Conversions
U(x)work if every type in the set converts to U. len, indexing,range,makehave extra rules. Up to Go 1.24 the spec phrased these rules in terms of a single "core type". Go 1.25 removed core types from the spec and replaced them with explicit per-operation rules. Behaviour is almost unchanged, but error messages no longer mention "core type".
type Point2 struct{ X, Y int }
type Point3 struct{ X, Y, Z int }
func GetX[T Point2 | Point3](p T) int {
// return p.X // compile error: p.X undefined (type T has no field or method X)
switch v := any(p).(type) {
case Point2:
return v.X
case Point3:
return v.X
}
return 0
}
func Length[T ~string | ~[]byte](a T) int { return len(a) } // OK: len valid for both
Field access is intentionally unsupported, even when every type has the field. The designers deferred it (issue #48522). The idiomatic fix is to define a method, such as GetX() int, and put it in the constraint. Interviewers are checking that you know constraints give you capabilities through methods and operators, not through structure.
More on Generics
- Q116Explain type sets. How do unions and intersections combine, and which interfaces can only be used as constraints?
- Q117What is
comparable? What changed in Go 1.20, and what does this program print? - Q119How does type inference work? When does it fail, and how do you order type parameters to make partial instantiation pleasant?
- Q120Can you store a generic function in a variable or pass it around without instantiating it?
- Q121How do you get and check the zero value of a type parameter
T? - Q122What does this print? (nil checks inside generic code)