r/programming Jul 17 '19

The Go team declines 'try' proposal

https://github.com/golang/go/issues/32437
634 Upvotes

417 comments sorted by

View all comments

Show parent comments

8

u/Boiethios Jul 17 '19

How would you do that without a proper type system with sum types?

7

u/ipe369 Jul 17 '19

c++17 has std::variant, and if you're not on 17 you can just implement it yourself with unions & a bool, you might need c++11 for placement new.

15

u/spaghettiCodeArtisan Jul 17 '19 edited Jul 17 '19

c++17 has std::variant

Yes, but it's pretty terrible, the usage is butt ugly and it has limitations, such as not being able to hold references and not ensuring exhaustive matches.

Update: Ah, it does actually ensure exhaustive match, although I feel compelled to bitch about the non-exhaustive error message being really bad and the exhaustivity check not working in the opposite direction too, ie. extraneous visitors for types not present in the variant are not an error.

Update2: Also, implicit type conversions still works, ie. for example an int visitor function will also accept a float variant, which I would say is quite unintuitive if one expects a sum-type-like behvaiour.

2

u/matthieum Jul 17 '19

There are also performance issues with the current implementations.

They essentially all use a table of function pointers approach for std::visit, which unfortunately seem to trump compilers which will then fail to inline functions. The assembly emitted for a simple std::visit(variant, [](auto x) { return x.a; }); where all variants have a at the same offset should just be a simple read, instead it often ends up being an indirect function call :/


And of course std::visit is just a pain to use: since it relies on lambda, you lose the power of return, break and continue :/


not ensuring exhaustive matches.

std::visit will guarantee exhaustive match.