4 ms·
I don’t think the Option presented here is sufficient (it is indeed a “crime”) as you cannot express Some(nil). But you could probably achieve that using go's
by Kostarrr 4y ago
I don’t think the Option presented here is sufficient (it is indeed a “crime”) as you cannot express Some(nil).
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/master/go/builder/staticOptional.go https://github.com/FSMaxB/type-safe-builder-experiment/blob/...
- jchw 4y agoI’m pretty sure that’s an interface union, not a sum type. That said, you could definitely do an option type using interfaces, but it would be less efficient than pointers directly because of the itab overhead.
- tsimionescu 4y ago> I’m pretty sure that’s an interface union, not a sum type. 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{} }`.
- jchw 4y agoI think that still eats the itab penalty so as long as the structures wind up with the same gcshape? But now I wonder.
- tsimionescu 4y agoWell, that doesn't really work, as "StaticOptional[T]" can't be used as the type of a variable. It can only be used to create another generic function. 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/1CnieCLqESC https://go.dev/play/p/1CnieCLqESC
- Kostarrr 4y agoMy bad. I was not aware on incredibly limited go generics are. I tried to make it work despite all restrictions but gave up here https://go.dev/play/p/XVTuJ--ZLgS https://go.dev/play/p/XVTuJ--ZLgS
- worg 4y agoI'm not well versed in golang generics (at $WORK we use go, but not generics yet) but if you want type switches you'll need interface{} to do that https://go.dev/play/p/1Tn2O_7vCTQ https://go.dev/play/p/1Tn2O_7vCTQ Which of course defeats the point of using generics _edit: clarify that my attempt is a bad practice_
- Koiwai 4y agoThat Option type is using pointer, not foremetioned Zero, &nil and nil are different things. https://go.dev/play/p/88We4TDhGQc https://go.dev/play/p/88We4TDhGQc
- dolmen 4y agoYou can store nil in an Option[any] or in any pointer type such as Option[*int].