Go

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, make have 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

All 36 Generics questions