| One annoying bit about Go's generics is that you can use type parameters in functions, but not in methods. So for example, maybe you'd want to write a Map function for the Optional type in this article, which returns None if the option is None, or calls a given function with the value of the Optional otherwise. You'd probably write it like this: func (o Option[T]) Map[U any](f func(a T) U) Option[U] { ... }
But that doesn't work: "option/option.go:73:25: methods cannot have type parameters"The type inference is also a bit limited, e.g: let's say you have a None method: func None[T any]() Option[T] { ... }
And you call it somewhere like: func someFunction() option.Option[int] {
if (!xyz) {
return option.None()
}
// ...
}
it isn't able to infer the type, so you have to instead (in this case) write option.None[int]().Generics is a super cool addition anyway though. Edit: I just found https://go.googlesource.com/proposal/+/refs/heads/master/des... which has some details on why method type parameters aren't possible. |
While you can't do this:
You can do this: So this is not quite as restricting as it seems. Though it is still likely to be annoying. Runnable example: https://gotipplay.golang.org/p/2w2y1KEjXVE