by Kostarrr · 4y ago · 0 comments
But you could probably achieve that using go's not-well-known sum types, e.g. like this
https://github.com/FSMaxB/type-safe-builder-experiment/blob/...
For example, this doesn't work [0]:
//compilation error: interface contains type constraints
func TryParse123(s string) StaticOptional[int] {
if s == "123" {
return StaticSome[int]{123}
}
return StaticNone{}
}
[0] https://go.dev/play/p/1CnieCLqESCWhich of course defeats the point of using generics
_edit: clarify that my attempt is a bad practice_
It's a kind of sum type, but it can only be used to constrain types for a generic parameter.
That is, you can define `func foo[T StaticOptional[int]](x T)` and then call it as `foo(StaticNone{})` or `foo(StaticSome[int]{123})`, but you can't do `func foo() StaticOptional[int]` or even `func foo[T StaticOptional[int]]() T {return StaticNone{} }`.