Hacker News new | ask | show | jobs
by alkonaut 2187 days ago
It guarantees that the value is set if the flag is saying it is set (that's the invariant of the type). It screams "check flag before accessing the value".

To compare with references which are also 0-or-1-thing effectively: A reference where you as a developer know it's never null but always a ref to exactly one thing is denoted "* T" and a reference to "one thing or null" is denoted "* T"! There is no difference in the types! so you can accidentally send one that is "0-or-1-things" to a method accepting a * T that MUST be a thing. Type system didn't help you document which case it was.

Options, apart from the annotation benefit it also helps making the syntax nicer in many cases, with e.g. "or()" fallbacks etc.

    let data = get_cached().or(load_from_disk()).or_panic();
1 comments

I agree that there are semantic issues with pointers, but my point was to illustrate that you need sum types in Go to get any real benefit out of an Option type. If you need an option type and you aren't content with a pointer, you can use `(T, bool)`, but this is still a far cry from a real Option type.
I use Option<T> types very happily in C# without sum types. Most of what would be pattern matching can be done with just methods.

    Car c = maybeCar.GetValueOr(CreateCar()) // inline fallback 

    maybeDog.Do(d => b.Bark()) // only performs call if present

    Sailboat s = mybeBoat.As<SailBoat>() // none unless of correct subtype
And so on. With nullable reference types C# now has a builtin alternative to this, but it has worked we’ll for many years.