Sobes.tech
Senior

What is missing in Go generics compared to other languages (e.g., C#)?

sobes.tech AI

Answer from AI

Generics in Go appeared relatively recently and are currently less feature-rich compared to languages like C#. The main limitations and what is lacking in Go generics compared to C#:

  • Limited type constraints: In Go, you can specify an interface as a constraint, but complex constraints, such as multiple inheritance of interfaces with specific methods, are not supported.
  • Lack of support for covariance and contravariance: C# generics support type variance, which simplifies working with inheritance and interfaces.
  • No support for special attributes and annotations for generics: C# allows the use of attributes to specify behaviors of generics.
  • Inability to constrain types by values (e.g., numeric constants): C# allows constraints like where T : struct, new() and others.

Example of a constraint in Go:

func SumIntsOrFloats[T int | float64](slice []T) T {
    var sum T
    for _, v := range slice {
        sum += v
    }
    return sum
}

In C#, you could implement more complex constraints and use covariance, which is not yet available in Go.

What is missing in Go generics compared to other… - sobes.tech