News for hackers. Stuff that matters.
Re:Switching from C++ to Rust by burntsushi on Monday March 13, 2023 @07:13PM (#35144548)
The call out to sum types is something I feel. I've been using Rust daily for almost 10 years now, and sum types are absolutely still one of the things I love most about it. It's easily one of the things I miss the most in other languages that don't have them. I'm usually a proponent of "using languages as they're intended," but I missed exhaustiveness checking so much that I ported a version of it to Go[1] as a sort of lint.

[1]: https://github.com/BurntSushi/go-sumtype

Re:Switching from C++ to Rust by paulddraper on Monday March 13, 2023 @07:20PM (#35144651)
Agreed. I don't have much Rust experience, but I do know Scala and Haskell and Typescript.

It's one of those patterns that just comes up again and again and it's wonderful when the language offers a good solution.

Re:Switching from C++ to Rust by auggierose on Monday March 13, 2023 @07:34PM (#35144843)
And I must say that Typescript has the most flexible variation of it. I remember a while ago (> 10 years) that somebody on Lambda the ultimate asked how to flexibly represent compiler intermediate representations using the Scala type system, given that there can be many of them with overlaps. These overlaps are not a problem at all in Typescript.
Re:Switching from C++ to Rust by paulddraper on Monday March 13, 2023 @07:39PM (#35144914)
Typescript has discriminated unions, which are amazingly nice
Re:Switching from C++ to Rust by olliej on Monday March 13, 2023 @07:37PM (#35144885)
Wait, are you saying that std::variant isn't a solution to all the problems? :D
Re:Switching from C++ to Rust by zabzonk on Monday March 13, 2023 @07:48PM (#35145009)
so, um, unions? i have to say that in many years of programming, i have almost never needed to use such types.
Re:Switching from C++ to Rust by burntsushi on Monday March 13, 2023 @07:52PM (#35145053)
Nope, not unions. Sum types. Sum types would be more analogous to tagged unions or discriminated unions.

> i have almost never needed to use such types

Well sure. When is an abstraction "needed"? Before Fortran, nobody "needed" a programming language either. So is a programming language necessary?

That's the funny thing about the word "need." It has very narrow application, and it's precisely why I didn't mention the word a single time in my top level comment.

Re:Switching from C++ to Rust by zabzonk on Monday March 13, 2023 @08:01PM (#35145166)
> Nope, not unions. Sum types. Sum types would be more analogous to tagged unions or discriminated unions

so, yes, unions.

Re:Switching from C++ to Rust by cornstalks on Monday March 13, 2023 @08:09PM (#35145254)
The union part is just an (obvious) optimization. An implementation detail. Sum types are not required to use a union; they can be implemented without using a union.
Re:Switching from C++ to Rust by zabzonk on Monday March 13, 2023 @08:15PM (#35145313)
how, exactly?
Re:Switching from C++ to Rust by cornstalks on Monday March 13, 2023 @08:18PM (#35145349)
By using a struct with lazily initialized members, for example.
Re:Switching from C++ to Rust by zabzonk on Monday March 13, 2023 @08:34PM (#35145510)
if that is your example, provide some code.
Re:Switching from C++ to Rust by cornstalks on Monday March 13, 2023 @09:07PM (#35145891)
Pretend we have the following sum type:

    enum SumType {
        Foo(foo),
        Bar(bar),
        Baz(baz),
    }

    void DoSomething(SumType sum_type) {
        match sum_type {
            Foo(foo): foo.do_x();
            Bar(bar): bar.do_y();
            Baz(baz): baz.do_z();
        }
    }
This could be lowered to:

    struct LoweredSumType {
        optional<Foo> foo;
        optional<Bar> bar;
        optional<Baz> baz;
    }

    void DoSomething(LoweredSumType sum_type) {
        if (sum_type.foo.has_value()) {
            sum_type.foo->do_x();
        } else if (sum_type.bar.has_value()) {
            sum_type.bar->do_y();
        } else {
            sum_type.baz->do_z();
        }
    }
This isn't real code; it's a pretend language that's kind of a mix of Rust and C++. But it illustrates that the sum type can be lowered into a non-union representation.
Re:Switching from C++ to Rust by zabzonk on Monday March 13, 2023 @09:33PM (#35146116)
> Pretend we have the following sum type:

which looks remarkably like a union to me, if i understand your made-up language.

Re:Switching from C++ to Rust by cdcarter on Monday March 13, 2023 @10:56PM (#35146806)
It's not a union, though, it stores references to three memory locations, not just one (as a union represents a single memory location which can have multiple possible interpretations). And the lowered code has nothing protecting it from an invariant where more than one reference is non-null!
Re:Switching from C++ to Rust by the-smug-one on Monday March 13, 2023 @08:52PM (#35145712)
Why does the members be lazily init:ed?
Re:Switching from C++ to Rust by cornstalks on Monday March 13, 2023 @09:00PM (#35145817)
If the data types have constructors and/or destructors that have side effects then it has to be lazy. Otherwise IMO it's not really behaving like a sum type.
Re:Switching from C++ to Rust by the-smug-one on Monday March 13, 2023 @08:50PM (#35145697)
struct List {}; struct Cons : public List { Cons(int v, List* nxt); int v; List* nxt; }; struct Nil : public List {};

This is how you'd do it in Java.

Re:Switching from C++ to Rust by zabzonk on Monday March 13, 2023 @08:58PM (#35145792)
and you would use it ... how?
Re:Switching from C++ to Rust by dcow on Tuesday March 14, 2023 @01:33AM (#35147773)
It's not exactly Java, but:

    Cons(1, Cons(2, Cons(3, Nil)))
Re:Switching from C++ to Rust by kaba0 on Tuesday March 14, 2023 @05:42AM (#35149156)
Actually, Java does have sum types nowadays, and you can write a recursive list implementation like “new Cons(2, new Cons(3, Nil.nil()))”.

Here is a definition for a Maybe type, converting it to a List is left as an exercise to the reader :) : https://news.ycombinator.com/item?id=35133670

Re:Switching from C++ to Rust by dcow on Tuesday March 14, 2023 @11:08AM (#35152708)
I just meant because I was eliding the `new`s.
Re:Switching from C++ to Rust by the-smug-one on Tuesday March 14, 2023 @04:55AM (#35148859)
I've showed you an alternative encoding, maybe get to work and learn something yourself?
Re:Switching from C++ to Rust by burntsushi on Monday March 13, 2023 @09:22PM (#35146026)
Based on your other replies in this thread, as far as I can tell, you're not here to try and understand something. You're here to fuck around and play games with people over definitions. So, I'm not responding to you. I'm responding to the people following along who might get confused by the mess you're making here. More to the point, the Wikipedia article for "sum type" redirects to "tagged union," which just honestly makes this more of a mess.

A tagged union is a specific kind of data structure. It essentially refers to a pair of information: the first is a tag and the second is the union. The union might represent many different kinds of values. The important bit is that the size of that memory is the size of the largest value. The tag then tells you what kind of value is in that memory, and crucially, tells you how to interpret that memory. Getting this wrong, for example, in a language like C can lead to undefined behavior.

Tagged unions show up in all sorts of places. The classical example is an AST. You usually have one "node" type that can be one of many possible things: a literal, a binary operation, a function call, a type definition, whatever. And for any non-primitive node, it usually has pointers to children. And what is the type of a child? Well, a "node"! It's a recursive data type. It lets you represent children as just more nodes, and those nodes might be any other AST node. (And as you might imagine, an AST can be quite a bit more complicated than this. You often want restrictions on which types of children are allowed in certain contexts, and so you wind up with many different tagged unions.)

The use of a tagged union like this can be conceptually thought of as a sum type. A sum type is not a data structure. A sum type is a concept. It comes from type theory and it is the "dual" of product types. Product types represent the conjunction of values while sum types represent the disjunction of values. In type theory notation, you usually see 'A x B x C' to refer to the product type of A, B and C. Similarly, you usually see 'A + B + C' to refer to the sum type of A, B or C.

A sum type can be represented by just about anything, because it's just a concept. You can take something that is typically used for product types and use it to present an API that gives you a sum type:

    type OptionInt struct {
        exists bool // private
        number int // private
    }
    
    func OptionIntNone() OptionInt {
        return OptionInt{false, 0}
    }
    
    func OptionIntSome(number int) OptionInt {
        return OptionInt{true, number}
    }
    
    func (o OptionInt) IsSome() bool {
        return o.exists
    }
    
    func (o OptionInt) Number() int {
        if !o.exists {
            panic("option is none, no number available")
        }
        return o.number
    }
This is a very contrived and hamstrung example, because it really doesn't give you much. But what it does give you is the API of a sum type. It is a value that can be either missing or present with an integer. Notably, it does not rely on any particular integer sentinel to indicate whether the value is missing or not. It encodes that state separately. So it can fully represent the presence of any integer value.

As you can see, despite it offering an API that represents the sum type concept, it is actually implemented in terms of a product type, or a struct in this case.

In a language like Go, which does not really support either unions or sum types, this sort of API is really hamfisted. In particular, one could object that it is a sum type because it doesn't really represent the "sum typeness" in the type system. Namely, if you get its use wrong, then you don't get a compilation error. That is, you can call the 'Number()' method without checking whether 'IsSome()' returns true or not. In other words, correct use of OptionInt looks like this:

    var opt OptionInt := doSomethingThatMightReturnNone()
    if opt.IsSome() {
        // OK, safe to access Number. It won't panic
        // because we just checked that IsSome() is true.
        fmt.Println(opt.Number())
    }
But nothing in Go stops you from writing this instead:

    var opt OptionInt := doSomethingThatMightReturnNone()
    fmt.Println(opt.Number())
This is why "support for sum types" is critical for making them as useful as they can be. In Rust, that same option type is defined like this:

    enum OptionInt {
        None,
        Some(i32),
    }
That's it. The language gives you the rest. And crucially, instead of splitting out the 'IsSome()' check and the access via 'Number()', they are coupled together to make it impossible to get wrong. So the above code for getting a number out looks like this instead:

    let opt: OptionInt = do_something_that_might_return_none()
    if let OptionInt::Some(number) = opt {
        println!("{}", number);
    }
You can't get at the 'number' without doing the pattern matching. The language won't let you. Now, you can define methods on your sum types that behave like Go's 'Number()' method above and panic when the value isn't what you expect. And indeed, Rust's Option and Result types provide this routine under the names 'unwrap()' and 'expect()'. But the point here isn't just about Option and Result, it's about sum types in general. And you don't have to define those methods that might panic. You can just let the language help guide you along instead.

Sum types are an idea. A concept. A technique. Tagged unions are an implementation strategy.

Notice also that I haven't mentioned exhaustiveness at all here. It isn't required for sum types. Haskell, for example, doesn't mind at all if your pattern matching isn't exhaustive. You actually have to tell it to warn you about it, and even then, it's not a compilation error unless you treat it as one. In Rust, exhaustiveness checking is enabled by default for all sum types. But you can disable it for a particular sum type with the '#[non_exhaustive]' attribute. The benefit of disabling it is that adding a new variant is possibly semver compatible change, where as adding a new variant in an exhaustive sum type is definitely a semver incompatible change.

Re:Switching from C++ to Rust by signa11 on Monday March 13, 2023 @10:59PM (#35146822)
this is just ... beautiful ! thank you !
Re:Switching from C++ to Rust by youainti on Monday March 13, 2023 @11:17PM (#35146962)
Thank you for such a great explanation. I found it to be really useful.
Re:Switching from C++ to Rust by kd5bjo on Tuesday March 14, 2023 @02:28AM (#35148057)
> But you can disable it for a particular sum type with the '#[non_exhaustive]' attribute.

I’m not sure this is the best description of what `#[non_exhaustive]` does in Rust. It doesn’t so much disable exhaustiveness checking as it marks the given list of variants as incomplete.

In Rust, some pattern matching contexts are required to be exhaustive (e.g. ‘let pattern = …;’, ‘match … {}’), and others are not (e.g. ‘if let … = … {}’). When an enum is tagged as ‘#[non_exhaustive]’, the former are required to include a wildcard matcher that will accept unknown variants, even if all known variants are explicitly matched.

Rust also allows structs to be `#[non_exhaustive]` to mark that the listed fields might not be sufficient. This disables the ability to (outside of a privacy boundary) directly construct an instance of the structure, or to destructure it with an exhaustive pattern.

Re:Switching from C++ to Rust by tialaramex on Tuesday March 14, 2023 @06:17AM (#35149381)
The privacy boundary applies in both cases by the way. Despite labelling your AmericanCity enum as #[non_exhaustive] since it only has Houston and Chicago in it so far, you are allowed in your own code inside the boundary to write a match which handles only Houston and Chicago. And that's actually probably a good idea, because when you add SanFrancisco to the enum, the compiler will point out anywhere your match clauses don't handle it, whereas if you had a default case (as your 3rd parties will) you'd drop into the default.
Re:Switching from C++ to Rust by burntsushi on Tuesday March 14, 2023 @08:19AM (#35150284)
My goal wasn't to describe it thoroughly, it was to call it out as a means of disabling exhaustiveness checking. Regardless of whether that's really what the essence of '#[non_exhaustive]' actually is, it does disable exhaustiveness checking. It's right in the name. It's an important part of what it does.

Basically, we're talking past each other. I called it out for what it does, but you're pointing out why someone would want to use it. That is, "#[non_exhaustive] on enums indicates that the list of variants is incomplete, and it does this by disabling exhaustiveness checking outside of the crate in which it is defined." Although, of course, not even that is precisely correct. Because your match arms are still forced to be technically exhaustive via the compiler requiring a wildcard arm. But the end effect to the user of the enum is that exhaustiveness checking on the variants of the enum is disabled.

Re:Switching from C++ to Rust by kaba0 on Tuesday March 14, 2023 @05:39AM (#35149136)
Thanks for the writeup!

Slightly unrelated, but re

> More to the point, the Wikipedia article for "sum type" redirects to "tagged union," which just honestly makes this more of a mess

I often see Wikipedia articles in CS topics severely lacking, or claiming exact definitions, when no such thing exists. Many definitions we regularly use are not exact at all, different papers/books use them differently, e.g. how would you even define OOP, low-level languages, etc? I would prefer them to use less strong language, as too many people argue on the internet based on Wikipedia definitions.

Re:Switching from C++ to Rust by burntsushi on Tuesday March 14, 2023 @08:13AM (#35150235)
I agree that they are lacking. In theory, I have the disposition to improve articles like that, but in practice, whenever I've tried, I get shut down by editors. It's been a long time since I've tried though.

It happens on other wikis too, like the Arch wiki.

I realize it's a tired complaint that a lot of people have and editors don't have an easy job, but I am so completely done with contributing to wikis. I know a lot of other people with the same complaint and same conclusion, including experts in the domain of type theory. One wonders whether this is one of the reasons why the articles are not as good as they could be.

Re:Switching from C++ to Rust by noobermin on Monday March 13, 2023 @10:38PM (#35146663)
Can you explain the utility of them over unions then? Asking sincerely.
Re:Switching from C++ to Rust by burntsushi on Monday March 13, 2023 @10:49PM (#35146749)
Unfortunately it's actually kind of difficult to parse your question because of the ambiguity in the surrounding comments. You could mean "tagged union" instead of "union," or maybe not and "them" means "tagged union"...

If you're asking to compare tagged unions and unions, then...

A union is not a tagged union. A union is part of a tagged union. A union on its own is just a region of memory. What's in that memory? I dunno. Who does? Maybe something about your program knows what it is. Maybe not. But what if you need to know what it is and some other aspect of your program doesn't tell you what it is? Well, you instead put a little bit of memory next to your union. Perhaps it an integer. 0 means the memory is a 32-bit signed integer. 1 means it's a NUL terminated string. 2 means it's a 'struct dirent'. The point is, that integer is a tag. The combination of a union and a tag is a tagged union.

An abstract syntax tree is a classic example of a tagged union.

If instead you're asking to compare tagged unions and sum types, then...

Tagged unions are one particularly popular implementation choice of a sum type. Usually sum types have additional stuff layered on top of them that a simple tagged union does not have. For example, pattern matching and exhaustiveness checking.

Re:Switching from C++ to Rust by noobermin on Monday March 13, 2023 @11:01PM (#35146844)
Sorry, yes I meant tagged union, a C style union (as in the language's concept) is so useless by itself that I thought being tagged was an obvious given.

In that case, the pattern matching and exhaustiveness means that the value the sumtypes in rust offer is in combination with those other language features, not the mere usage of the sumtypes themselves then, I think that makes more sense.

Re:Switching from C++ to Rust by burntsushi on Monday March 13, 2023 @11:11PM (#35146921)
Yes. When you say "sum type" and you're talking about, say, Ocaml or Standard ML or (mostly) Haskell or Rust, then what comes with that is also the infrastructure around sum types in those languages. They aren't really separable. That includes pattern matching and exhaustiveness checking (the latter is an opt-in warning in Haskell, and can be opted out of in Rust on a per-type basis).

The discussion around "sum type" the concept is to disentangle it from the implementation strategy. Tagged unions are the implementation strategy, and they don't come with pattern matching or exhaustiveness checks.

Of course, many of these terms are used interchangeably in common vernacular. But if you look at the comment that kicked off this annoying sub-thread:

> so, um, unions? i have to say that in many years of programming, i have almost never needed to use such types.

Then this is clearly trying to draw an equivalence between two different terms, but where no such equivalence exists. There's no acknowledgment here of the difference between what a "union" is (nevermind a tagged union) and the "sum types" being talked about in my original top level comment. And the last part, "i have almost never needed to use such types" is puzzling on multiple levels.

Re:Switching from C++ to Rust by dralley on Monday March 13, 2023 @07:51PM (#35145044)
Tagged unions with exhaustiveness checking, built into the language in a fairly deep way. Very different from what would come to mind for a C or C++ developer who hears the word "union".
Re:Switching from C++ to Rust by edgyquant on Monday March 13, 2023 @08:25PM (#35145410)
I can’t imagine not having the ability for a variable to be one of multiple potential types. I could probably work around it, sure, but why would you want to?
Re:Switching from C++ to Rust by zabzonk on Monday March 13, 2023 @08:32PM (#35145498)
i can't imagine why you would want that. for example, why would i want something defined as an integer hold something other than an integer? this is how strongly-typed languages work.
Re:Switching from C++ to Rust by Twisol on Monday March 13, 2023 @08:54PM (#35145743)
Scott Wlaschin's "F# For Fun and Profit" website is a great resource for strongly-typed (yes) data modeling with sum types as a fundamental tool.

https://fsharpforfunandprofit.com/series/designing-with-type...

By the third entry in the linked series, we've motivated the use of a sum type with three variants in the example domain model.

Re:Switching from C++ to Rust by lmm on Tuesday March 14, 2023 @02:09AM (#35147955)
You definitely want an integer to always be an integer, but you often want to represent "A or B". E.g. user has a contact method that's a phone number or an email address. Result of validation is a validated value or a failure message.
Re:Switching from C++ to Rust by nicoburns on Monday March 13, 2023 @08:19PM (#35145355)
Does your code ever contain class hierarchies with a fixed set of classes? Or variables where certain values have special case meaning? Those are the cases where Sum Types make things immeasurably nicer than the alternatives.
Re:Switching from C++ to Rust by zabzonk on Monday March 13, 2023 @08:29PM (#35145461)
> Does your code ever contain class hierarchies with a fixed set of classes?

no - one of the advantages of OO programing is that class hierarchies (should you feel the need to use them, which mostly i do not) can be expanded. or indeed contracted.

> Or variables where certain values have special case meaning?

very, very rarely (i would say never, in my own code) but of course we have the null pointer as a counter-example. to which i can say: don't use raw pointers.

Re:Switching from C++ to Rust by jjnoakes on Monday March 13, 2023 @09:09PM (#35145913)
Do you have any large open source code bases that you could share?
Re:Switching from C++ to Rust by kaba0 on Tuesday March 14, 2023 @05:45AM (#35149180)
The Visitor pattern, which is a must in certain niches is exactly analogous to pattern matching over a sum type, and I am fairly certain that I can objectively say that the latter is a million times more readable and maintainable.

It doesn’t make OOP obsolete, though, at all. Certain other areas are better expressed as hierarchies, e.g. GUI nodes.

Re:Switching from C++ to Rust by cmrdporcupine on Monday March 13, 2023 @08:25PM (#35145420)
The C++ (or Java etc) way to do many of the kind of things people do with Rust pattern matching & sum types would be via OO subtyping polymorphism. e.g. classic visitor pattern, etc. Way more verbose and awkward, and scatters the logic all over the place.

Enums + switch is the other, and far less powerful.

Re:Switching from C++ to Rust by thom on Tuesday March 14, 2023 @04:05AM (#35148560)
Or, for the case of errors, with exceptions, which happen to have their own very limited pattern matching syntax.
Re:Switching from C++ to Rust by kaba0 on Tuesday March 14, 2023 @05:48AM (#35149203)
I swear I am not paid to shill for Java or anything…, but Java did get sum types recently, and it’s quite good. They made it in a backwards compatible manner by sealed classes that list all of its subtypes.

Switch expressions were also implemented, and they can exhaustively match on the given sum type. Pattern matching is quite limited as of now (only usable with records), but it is coming.

Re:Switching from C++ to Rust by cmrdporcupine on Tuesday March 14, 2023 @07:43AM (#35149977)
I should take a look. I kind of have a nostalgic interest in looking back at the JVM again, as 10 years ago it was my main career.

The problem with Java was always that it has moved so slowly in acquiring nice things. The actual core runtime is amazingly well engineered.

Re:Switching from C++ to Rust by mgsloan2 on Monday March 13, 2023 @08:46PM (#35145651)
In my experience with languages that lack concise sum types and pattern matching, you end up with data types that have lots of implicit invariants. If you find yourself writing docs or thinking in your head things like "Field X is only set if field Y is true" or "If field X is non-null then field Y must be null and vice-versa", then these are indications that sum types would model the data better. Then these invariants can be followed by construction, and it becomes clear what's available at data access - great for interface clarity, robustness, dev tools, morale, etc.

Relatedly, storing booleans is a smell, imho typically an enum or sum type is always better in languages that have concise syntax for these. True and False are meaningless without context, and so can easily lead to errors where they are provided to a different context or generally misused due to a misunderstanding about the meaning.

Re:Switching from C++ to Rust by zabzonk on Monday March 13, 2023 @09:37PM (#35146158)
i agree with your first point, but if your type-system is sufficently strong to express this, i'd like to see an example.

i agree completely with your second point - passing around or storing booleans is usually horrible.

Re:Switching from C++ to Rust by mgsloan2 on Monday March 13, 2023 @11:19PM (#35146975)
> if your type-system is sufficently strong to express this

No fanciness needed, just plain old sum types. It is certainly possible to express those invariants directly in languages with a dependent type systems or refinement types like in liquid haskell - see https://ucsd-progsys.github.io/liquidhaskell-tutorial/Tutori.... It's typically much easier to reason about and use sum types, though.

Of course these examples are trivial and silly, but I see instances of these patterns all the time in big co software, and of course usually the invariants are far more complex but many could be expressed via sum types. I've seen loads of bugs from constructing data that invalidates assumptions made elsewhere that could have been prevented by sum types, as well as lots of confusion among engineers about which states some data can have.

> Field X is only set if field Y is true

Original gnarly C style pattern:

    struct TurboEncabulatorConfig {
        // When true, the turbo-encabulator must reticulate splines, and 'splines'
        // must be non-null. When false, 'splines' must be null.
        bool reticulate_splines;
        struct Splines *splines;
    };
Rust (let's ignore pointer vs value distinction):

    enum TurboEncabulatorConfig {
        NonReticulatingConfig,
        ReticulatingConfig { splines: Splines },
    }
> If field X is non-null then field Y must be null and vice-versa.

Original gnarly C style pattern:

    struct TurboEncabulatorConfig {
        // When non-null, lunar_waneshaft must be null. 
        struct Fan *pentametric_fan;
        // When non-null, pentametric_fan must be null.
        struct Shaft *lunar_waneshaft;
    };
Rust:

    enum TurboEncabulatorConfig {
        PentametricTurboEncabulator { pentametric_fan: Fan },
        LunarTurboEncabulator { lunar_waneshaft: Shaft },
    }
Re:Switching from C++ to Rust by fulafel on Tuesday March 14, 2023 @02:51AM (#35148171)
Type systems are of course not the only possible mechanism that can enforce these kinds of invariants. In dynamic languages, schema style solutions (eg malli or spec in Clojure) have advantages: they have more expressivity than typical type systems, you can manipulate them as data, you can use in contexts that are not statically verifiable, like at the data interfaces of yuor app.
Re:Switching from C++ to Rust by mejutoco on Tuesday March 14, 2023 @05:32AM (#35149076)
I agree it has more flexibility, but more expressiveness is a double edged sword. Type systems are often not Turing-complete, or at least they are limited in some ways. A language being very expressive means it cannot be run at compile time, sine we cannot know if it terminates.

If we cannot run it at runtime now we need tests to hit that path or to test it manually to actually know if it works.

Re:Switching from C++ to Rust by epage on Monday March 13, 2023 @07:59PM (#35145134)
To me its not just exhaustiveness but that sum types (enums) are just like product types (structs), they have have member methods, implement traits, etc. Coming from C++, when I realized Rust let me do that, it blew me away.
Re:Switching from C++ to Rust by jcranmer on Monday March 13, 2023 @08:10PM (#35145261)
A union in C++ is the same thing as a struct, except all of its fields live at the same offset. So you can define any method you want on it, including special stuff like constructors and destructors. No base classes are allowed, though.
Re:Switching from C++ to Rust by nicoburns on Monday March 13, 2023 @08:26PM (#35145433)
A method on a union is much less useful when you can't match on the tag though. I suppose you could store tag inside the union. Is that common? I've always imagined C/C++ tagged unions would store tag outside the union.
Re:Switching from C++ to Rust by umanwizard on Monday March 13, 2023 @08:44PM (#35145627)
Yes, it’s very common. The difference is rust enforces via the type system that you match on it.
Re:Switching from C++ to Rust by dilap on Monday March 13, 2023 @09:04PM (#35145855)
i haven't done c++ in a million years, but huh, you can! can't have any types w/ non-trival copy constructors in a union, though, apparently, which is quite the restriction.

https://gist.github.com/erinok/c823af95db408653c7e42ab189307...

Re:Switching from C++ to Rust by ivmaykov on Monday March 13, 2023 @09:26PM (#35146069)
I may be wrong, but I thought it’s that you can’t have any fields with non trivial destructors, because the union wouldn’t know which destructor to call. So POD types / raw pointers / arrays of the above / structs of the above are allowed, and that’s pretty much it.
Re:Switching from C++ to Rust by gpderetta on Monday March 13, 2023 @10:33PM (#35146627)
You can have non trivial types in an union, but you need to explicitly define constructor in the union or the containing type (i.e. the default union copy constructor and assignment operator are disabled).
Re:Switching from C++ to Rust by jcranmer on Tuesday March 14, 2023 @12:24AM (#35147432)
> can't have any types w/ non-trival copy constructors in a union, though, apparently, which is quite the restriction.

That was removed in C++11. The rule now is:

> Absent default member initializers ([class.mem]), if any non-static data member of a union has a non-trivial default constructor ([class.default.ctor]), copy constructor, move constructor ([class.copy.ctor]), copy assignment operator, move assignment operator ([class.copy.assign]), or destructor ([class.dtor]), the corresponding member function of the union must be user-provided or it will be implicitly deleted ([dcl.fct.def.delete]) for the union.

i.e., you need to provide an explicit version of the special function for the union if any member has a nontrivial implementation.

Re:Switching from C++ to Rust by dilap on Tuesday March 14, 2023 @12:38PM (#35154258)
ah, good to know, thanks! unfortunately too late to edit my comment
Re:Switching from C++ to Rust by ivmaykov on Monday March 13, 2023 @09:22PM (#35146033)
You would probably use std::variant in C++ if you want tagged unions.

So you could have a struct or class with one std::variant field and some methods which can match on the type of the variant. But it would be kind of clunky.

Re:Switching from C++ to Rust by unwind on Tuesday March 14, 2023 @04:42AM (#35148777)
At least in C, you cannot store a tag inside the union since all fields of the union live at the same offset (0) they tag will be smashed by the actual value it's trying to talk about.

In C, you have to wrap the union in a struct in order to add the tag, and that pattern is fantastically common. Let's have a little geometry-inspired example:

    typedef enum { SHAPETYPE_RECTANGLE, ... } ShapeType;
    typedef struct { ... } Rectangle;
    typedef struct { ... } Circle;
    typedef struct { ... } Triangle;
    typedef struct { ... } Polygon;

    typedef struct { // Outer struct, not a union at this level.
      ShapeType type;
      union {
        Rectangle rectangle;
        Circle    circle;
        Triangle  triangle;
        Polygon   polygon;
      }  // This can be nameless in new(ish) C, which is nice.
    } Shape;
Then you'd create a value like this, maybe:

    Shape rect = { .type = SHAPETYPE_RECTANGLE, .rectangle = { 0, 0, 20, 10 } };
Of course wrapping the initialization in a function would make it nicer.

The above union-in-a-struct wrapping is my mental model for how enums work in Rust, but I still find it jarring. :)

Re:Switching from C++ to Rust by tialaramex on Tuesday March 14, 2023 @05:27AM (#35149042)
I'm not certain for C, but definitely in C++ it's legal to union a bunch of structures with a common prefix, and then talk about the prefix in the "wrong" variant and that's OK. There may be some restrictions about exactly what is in that prefix, but at least obvious things like an enum or an integral type will work.

So for your example you put ShapeType type in each of Rectangle, Circle, Triangle etc. and then you can union all of them, and the language promises that shape.circle.type == Rectangle is a reasonable thing to ask, so you can use that to make a discriminated union.

Re:Switching from C++ to Rust by staunton on Tuesday March 14, 2023 @06:50AM (#35149571)
> I'm not certain for C, but definitely in C++ it's legal to union a bunch of structures with a common prefix, and then talk about the prefix in the "wrong" variant and that's OK

That doesn't sound right to me. Do you have a source? Is that in the standard?

Re:Switching from C++ to Rust by unnah on Tuesday March 14, 2023 @07:57AM (#35150093)
I don't know about the standard, but if cppreference.com is good enough: At https://en.cppreference.com/w/cpp/language/union it says "If two union members are standard-layout types, it's well-defined to examine their common subsequence on any compiler."
Re:Switching from C++ to Rust by tialaramex on Tuesday March 14, 2023 @09:22AM (#35151032)
I of course do not own a copy of the expensive ISO document, however, in the draft:

11.5.1 [class.union.general]

[Note 1: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence ([class.mem]), and if a non-static data member of an object of this standard-layout union type is active and is one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of the standard-layout struct members; see [class.mem]. — end note]

Re:Switching from C++ to Rust by unwind on Tuesday March 14, 2023 @08:00AM (#35150119)
Yes, totally. Good point, I forgot about that technique. I prefer this, which is less invasive.
Re:Switching from C++ to Rust by planede on Tuesday March 14, 2023 @07:30AM (#35149869)
C++ allows accessing inactive members in the special case when the active member shares a "common initial sequence" with the particular inactive member.

So yeah, it's possible to store the tag in the common initial sequence of all the union members.

This is quite niche and rarely used. Most of the time it makes more sense to have the tag outside. Sometimes the tag in the common initial sequence allows the whole data structure to pack better than with a tag outside of the union.

Re:Switching from C++ to Rust by tomjakubowski on Monday March 13, 2023 @08:05PM (#35145212)
In fairness to C++, you could derive a class from std::variant and add methods to it that way.

It's less awkward with Rust's enums for sure though. And pattern matching as in Rust is far more expressive (and legible) than what std::variant gives you.

Re:Switching from C++ to Rust by tialaramex on Monday March 13, 2023 @09:07PM (#35145889)
Actually all three of Rust's user defined types (the sum type enum, the product type struct, and union†) are fully fledged types which can implement traits and have functions of their own (including functions taking a self parameter, thus methods)

C++ unions can actually have methods, although this isn't used very much. However C++ enums can't have methods, even C++ 11 scoped enums ("enum classes") can't have methods, I have no idea why that restriction seemed like a good idea.

† Unions are special because they're crazy dangerous, which is why they're not usually covered in material for learning Rust - you can't fetch from them safely. You can store things in unions safely because the process of storing a value in a union tells the compiler which is the valid representation - the one you're storing to, but fetching is unsafe because you might fetch an inactive representation and that's UB. However Rust does have a particularly obvious union right in the standard library - MaybeUninit - and sure enough MaybeUninit implements Copy and has a bunch of methods.

Re:Switching from C++ to Rust by delta_p_delta_x on Monday March 13, 2023 @11:31PM (#35147069)
> C++ enums can't have methods, even C++ 11 scoped enums ("enum classes") can't have methods, I have no idea why that restriction seemed like a good idea

It is possible that Oracle holding the patent[1] to methods on enums is the blocker, rather than any technical restriction.

[1]: https://patents.google.com/patent/US7263687

Re:Switching from C++ to Rust by justusw on Tuesday March 14, 2023 @12:31AM (#35147473)
That sounds bizarre. So this means that parents are potentially holding back programming language innovation? I hope I don’t have to consult with a lawyer every time I invent a new variation on the for loop. (I anticipate that someone will then tell me that there already is a patent for that…)
Re:Switching from C++ to Rust by TheDong on Tuesday March 14, 2023 @02:11AM (#35147963)
Why would it be bizarre? It's not exactly a fringe belief that patents in all software are holding back innovation.

I don't think programmers often consult 20 year old "inventions", so it seems pretty obvious on its face that the supposed benefit of patents, that something is _only_ locked up for 20 years, is quite pointless in software.

Anyway, for loops are safe, unless the for loop is over the elements of a linked list. Then you need to wait until next year: https://patents.google.com/patent/US7028023B2

Re:Switching from C++ to Rust by planede on Tuesday March 14, 2023 @07:26AM (#35149831)
Doesn't that patent's claims cover doubly-linked lists? The "auxilary order" could very well be reverse order. Seems like an obvious prior art.
Re:Switching from C++ to Rust by kaba0 on Tuesday March 14, 2023 @05:28AM (#35149047)
I am absolutely not a lawyer, but wouldn’t it fall into the “trivial” category, so even if patented, it couldn’t be enforced?
Re:Switching from C++ to Rust by capableweb on Tuesday March 14, 2023 @06:12AM (#35149363)
Problem is, unless it has been tried in court, you can't be certain. And if you're building something, you might not want to spend time in court having to fight it in the first place. So even if it's 50/50 enforceable/not enforceable, do you really want to spend the time testing if it is?

Patents really have a chilling effect, even if a particular one might not be enforceable.

Re:Switching from C++ to Rust by planede on Tuesday March 14, 2023 @07:21AM (#35149777)
Also the ISO is also very averse of patents. They will probably not standardize anything patent-encumbered. They would probably require invalidating the patent first before accepting it in the standard.

Having said that this is the first time I ever heard of methods on enums being patented, what a ridiculous patent. It's a good thing then that C++ doesn't have methods, it has "member functions" :).

Also C++ allows user defined operators on enums, which feels somewhat adjacent.

Re:Switching from C++ to Rust by tialaramex on Tuesday March 14, 2023 @10:32AM (#35152155)
WG21 (the "C++ Committee") is under JTC1 the Joint Technical Committee ("joint" between ISO and IEC), now, you might know of a few other famous products of the Joint Technical Committee's sub and sub-sub committees, including JPEG (that's the Joint Photographic Experts Group getting a shout out in the name of the standard) and MPEG. Those standards both required patented "inventions" to implement in full. The patents were held by contributors...

In the case of MPEG the result is MPEG LA, a US company which you need to pay to implement certain important standards. In the case of JPEG the result was a little different, since only the improved Arithmetic Coding of JPEG was patented, people just don't implement the actual standard, they cut out the patented part, so all the world's JPEGs (well, mostly JFIF files, which are slightly different but we call them "JPEGs" anyway) are a little bigger than they need to be for no reason except patents.

So no, I don't buy that "ISO is also very averse of patents" in a sense that would restrict this unless you can show that's a new stance.

Re:Switching from C++ to Rust by planede on Tuesday March 14, 2023 @11:38AM (#35153258)
Yeah, good point. But I think this still applies to WG21.
Re:Switching from C++ to Rust by criddell on Tuesday March 14, 2023 @07:14AM (#35149734)
That expires in 2024, so perhaps the next version of C++ will have it.
Re:Switching from C++ to Rust by evntdrvn on Tuesday March 14, 2023 @05:11AM (#35148941)
I just wish that Rust’s enum Variants were types… maybe someday! :)
Re:Switching from C++ to Rust by epage on Tuesday March 14, 2023 @07:42AM (#35149970)
Since I've heard of this idea, I keep finding places where id use it, whether that be for variant-specific behavior or to remove the redudant type definitions in my API.
Re:Switching from C++ to Rust by zaphar on Tuesday March 14, 2023 @08:12AM (#35150221)
It's not exactly what you want but you get most of the benefit by just wrapping types in enum variants.
Re:Switching from C++ to Rust by evntdrvn on Tuesday March 14, 2023 @11:34AM (#35153197)
Thanks yeah, I was just meaning for the ergonomics aspect :) Cheers
Re:Switching from C++ to Rust by estebank on Tuesday March 14, 2023 @06:09PM (#35159696)
It's a request for the following to be valid

    enum X {
        A,
        B,
    }
    fn foo() -> X::A {
        X::A
    }
which helps a lot when composing state machines. In the meantime, you can indeed do what you propose:

    enum X {
        A(Foo),
        B(Bar),
    }
    struct Foo;
    struct Bar;
    fn foo() -> Foo {
        Foo
    }
Re:Switching from C++ to Rust by loeg on Monday March 13, 2023 @08:16PM (#35145322)
Yeah. In the C++ codebase I work on, we use folly::Expected<T, E> (essentially similar to Rust's Result<T, E>) heavily. Is it as ergonomic as Result is in Rust? Absolutely not. But it's still a nice design pattern for some of the same reasons people use Result in Rust.

(And C++ std::optional<T> is somewhat similar to Rust's Option<T> type.)

https://github.com/facebook/folly/blob/main/folly/Expected.h...

Re:Switching from C++ to Rust by cmrdporcupine on Monday March 13, 2023 @08:23PM (#35145389)
Sounds like Google/abseil's "StatusOr', but maybe a bit more freefrom?

https://abseil.io/docs/cpp/guides/status

Re:Switching from C++ to Rust by loeg on Monday March 13, 2023 @08:32PM (#35145500)
Yeah, we use a fixed-E alias of folly::Expected<> in our codebase which is similar to absl::StatusOr. Something like:

  namespace our_project {
    class Status { ... };
  
    template <class T>
    using Expected = folly::Expected<T, Status>;
  }
absl::StatusOr<T> looks a lot like our_project::Expected<T>.
Re:Switching from C++ to Rust by joenot443 on Monday March 13, 2023 @09:05PM (#35145866)
Swift has a similar Result type, it’s very handy.
Re:Switching from C++ to Rust by tcmart14 on Tuesday March 14, 2023 @12:40AM (#35147523)
Swift on linux is supposed to be decent server side, but as far as I've heard, not much use outside of that and even limited testimonials on that. The bit I have dabbled in Swift, I really like it. I just wish it grew more out of the Apple ecosystem. It has lots of things I like, but considering I can't exactly take it with me to any system and just run with it is why I have not dived to much into it.
Re:Switching from C++ to Rust by klabb3 on Tuesday March 14, 2023 @01:15AM (#35147681)
Is swift outside of Apple as fully fledged and performant when it comes to concurrency? Last I checked, a lot of the heavy lifting came from GCD (ie the Apple runtime-scheduler)
Re:Switching from C++ to Rust by Volt on Thursday March 16, 2023 @09:35PM (#35191672)
GCD is open source and runs on FreeBSD and Linux.
Re:Switching from C++ to Rust by hiccuphippo on Tuesday March 14, 2023 @08:23AM (#35150327)
Take a look at Zig (but it's not stable yet, may take a couple of years), linux is a first class citizen for it. It has `error!type` unions and `?type` optionals and language constructs to deal with them:

    const number = try parseU64(str, 10); // returns the error
    const number = parseU64(str, 10) catch 13; // default
    // more complex stuff
    if (parseU64(str, 10)) |number| {
        doSomethingWithNumber(number);
    } else |err| switch (err) {
        error.Overflow => {
            // handle overflow...
        },
        // we promise that InvalidChar won't happen (or crash in debug mode if it does)
        error.InvalidChar => unreachable,
    }
Re:Switching from C++ to Rust by tcmart14 on Tuesday March 14, 2023 @03:18PM (#35156966)
I've been checking out Zig over the past week. It is a really nice language and I like so far. Just not spending as much time as I'd like in it since it is still pre-1.0, but I am excited for it's 1.0.
Re:Switching from C++ to Rust by mgraczyk on Monday March 13, 2023 @10:49PM (#35146747)
Worth mentioning that C++23 adds something very similar to the standard library, called std::expected.

https://en.cppreference.com/w/cpp/utility/expected

Unfortunately it does not come with nice syntax to return on error.

Re:Switching from C++ to Rust by loeg on Tuesday March 14, 2023 @12:48PM (#35154425)
Nice.

> Unfortunately it does not come with nice syntax to return on error.

Yeah. We use a C preprocessor macro for this, but it's a little more verbose than question-mark operator.

Re:Switching from C++ to Rust by raincole on Monday March 13, 2023 @08:19PM (#35145352)
> I've been using Rust daily for almost 10 years now,

I'm just nitpicking but Rust is 7 years old and 7 doesn't feel almost 10...

Re:Switching from C++ to Rust by riceart on Monday March 13, 2023 @08:28PM (#35145451)
If you’re going to nitpick you better be right, and you’re not. - and I think he might be too humble to say anything but you might want to look into who you’re replying to and their body of work.

Rust has been around for well over a decade - the first “stable” release was 7 years ago. It’s always been opensource - any random hacker could download it and start using it since it was available. I think you will find kind quite a few people on this site that took it for a spin when it was still under development.

I have nowhere near the credits of BurntSushi, and even I was dabbling with rust more than 7 years ago.

Don’t be a reply guy.

Re:Switching from C++ to Rust by raincole on Monday March 13, 2023 @08:48PM (#35145674)
He did replied, and I apologize for being ignorant.
Re:Switching from C++ to Rust by capableweb on Monday March 13, 2023 @08:21PM (#35145373)
Rust was initially created in 2006. Mozilla started sponsoring Rust in 2009. Maybe you're talking about the first stable release, which happened in 2015? Rust has been around for longer than the first stable release though.

First spike at Google Trends for "Rust (Programming Language)" happened back in late 2013/early 2014 (https://trends.google.com/trends/explore?date=all&q=%2Fm%2F0...) so not at all impossible for someone to have ~10 years experience with it. Although that's probably pretty uncommon.

As a bonus, here is a very old (by internet time standards) HN submission titled "Mozilla releases version 0.1 of the Rust programming language (mail.mozilla.org)" - 236 points | Jan 23, 2012 | 82 comments - https://news.ycombinator.com/item?id=3501980

Re:Switching from C++ to Rust by nightpool on Monday March 13, 2023 @08:27PM (#35145438)
The person you're replying to, BurntSushi, is one of the most well-known Rust library authors and has been publishing open source Rust code since (at least) March of 2014, when the initial commits on the old regex crate were recorded. That's 9 years, just based off of a random quick Github search, which was hardly exhaustive.
Re:Switching from C++ to Rust by burntsushi on Monday March 13, 2023 @08:25PM (#35145413)
Yeah as other have mentioned, I was using Rust before 1.0.

This is my first public commit: https://github.com/BurntSushi/quickcheck/commit/c9eb2884d6a6...

I didn't write any substantive Rust before that point. So I'm at over 9 years.

Re:Switching from C++ to Rust by raincole on Monday March 13, 2023 @08:26PM (#35145425)
oh I see. Sorry I didn't expect you're such an early adopter.
Re:Switching from C++ to Rust by nicoburns on Monday March 13, 2023 @08:23PM (#35145398)
Rust hit 1.0 is 7 years ago. But burntsushi has been using Rust since before it hit 1.0
Re:Switching from C++ to Rust by howinteresting on Monday March 13, 2023 @08:21PM (#35145377)
BurntSushi has been using Rust since before 1.0.
Re:Switching from C++ to Rust by howinteresting on Monday March 13, 2023 @08:23PM (#35145399)
I'm going to make the even stronger claim that a general-purpose statically typed language that doesn't support sum types and exhaustive pattern matching to at least the extent that Rust does is unfit for general use, just like a language that doesn't have product types is unfit for general use.

Dynamically-typed languages often have adhoc sum types.

Re:Switching from C++ to Rust by unclad5968 on Monday March 13, 2023 @08:55PM (#35145748)
Well that's obviously not true given all the successful apps written in languages that don't support sum types.
Re:Switching from C++ to Rust by tialaramex on Monday March 13, 2023 @09:14PM (#35145956)
It depends what you take "unfit" to mean.

Suppose I say that cars without seatbelts are "unfit" to use on public roads. Clearly I can't mean it's impossible to use such cars, people used to do it all the time, but perhaps I mean it's a bad idea to use them, and that's harder to argue with which is why we got laws saying you need seatbelts.

Re:Switching from C++ to Rust by andrewflnr on Monday March 13, 2023 @09:49PM (#35146255)
A lot of successful apps were written with GOTO. That doesn't mean it's a good idea now.
Re:Switching from C++ to Rust by mikebenfield on Monday March 13, 2023 @09:24PM (#35146045)
I know your claim will strike some people as absurd, but I agree. I am honestly flabbergasted that any general purpose language created in the last 20 years doesn't have sum types and pattern matching. To me they are very nearly as fundamental as aggregate types (aka structs or product types).
Re:Switching from C++ to Rust by johnny22 on Monday March 13, 2023 @10:12PM (#35146444)
even php has some level of pattern matching now.
Re:Switching from C++ to Rust by the_gipsy on Tuesday March 14, 2023 @08:29AM (#35150399)
What does php not have by now, is the question.
Re:Switching from C++ to Rust by gnulinux on Monday March 13, 2023 @09:24PM (#35146049)
This is exactly what I think too. Sum types are so powerful, I feel a lot safer in Python + mypy with sum types (`from typing import Union`) than anything with C++ [1] even though C++ has a significantly more complex type system (it's type system is TC) and Python is as type-unsafe as a language can get. C++ made this odd choice as if any complex type system is better than a simple type system. When I was a younger software engineer, I agreed with this choice but now I completely disagree. I think next generation of software engineers will see that Turing completeness is a bug, and that the whole thing about software safety is finding weak features that are just powerful enough to be useful. If you don't believe me, go look at a language like Agda. You do not need Turing completeness: function application, sum types, primitive/structural recursion/corecursion are just about everything you need as a programmer and everything else that gives you a Turing complete language is extraneous.

[1] unless you liberally use `union`s everywhere which is very unidiomatic C++, but can be done if desired.

Re:Switching from C++ to Rust by aw1621107 on Monday March 13, 2023 @11:01PM (#35146840)
> even though C++ has a significantly more complex type system (it's type system is TC)

For what it's worth, Python's type hints are also Turing complete (https://arxiv.org/abs/2208.14755, discussed on HN at https://news.ycombinator.com/item?id=32779296)

Re:Switching from C++ to Rust by umanwizard on Tuesday March 14, 2023 @02:38AM (#35148098)
Rust’s type system is also Turing complete: https://sdleffler.github.io/RustTypeSystemTuringComplete/
Re:Switching from C++ to Rust by Sparkyte on Tuesday March 14, 2023 @02:56AM (#35148196)
You can just make your python modules out of another language. I am not sure why code has to be big. Break it down and make it executive, not very friendly in terms of threads but if you're writing an API you are writing it for Linux which is vastly safer for threads than Microsoft or Mac.

https://developers.redhat.com/blog/2017/11/16/speed-python-u...

Re:Switching from C++ to Rust by pharmakom on Tuesday March 14, 2023 @03:30AM (#35148366)
C++ has std::variant though?
Re:Switching from C++ to Rust by OnlyMortal on Tuesday March 14, 2023 @03:57AM (#35148522)
… and boost::variant if you’re either using an old code base or want to use boost serialization.
Re:Switching from C++ to Rust by dureuill on Tuesday March 14, 2023 @04:16AM (#35148622)
Yes, but:

- nobody uses it in the ecosystem. As outlined in the article, a lot of value of Option/Result is derived from their pervasiveness in the Rust ecosystem. C++ is far from this

- the ergonomics of it are terrible: no pattern matching, structural variants instead of named variants (yes you can emulate that with wrapper types but meh), lambda-oriented matching means you cannot as easily do things like early returns, statement-oriented language limits the usefulness anyway, lack of combinators, and for error handling specifically, lack of `?` operator

- performance is dubious. I had very steep and unexpected performance cliffs when lambda inlining started to fail for some reason. Having sum types be a language construct guarantees we're not relying on things like lambda optimisation here.

Re:Switching from C++ to Rust by blub on Tuesday March 14, 2023 @04:23AM (#35148659)
Variant types where one has to use objects as types don’t come up that often in API design or data structures in my experience with mobile and system programming on e.g. Linux. I think I’ve genuinely had to use them only a few times.

Error types are probably the most popular incarnation of that. There’s several libraries available and they will be part of the C++ standard.

This is a case of the Rust community overselling a minor feature as a game-changing novelty.

Re:Switching from C++ to Rust by 3836293648 on Tuesday March 14, 2023 @05:18AM (#35148983)
You clearly haven't tried using variant types properly then. Sure, `std::variant` is pretty unergonomic, but they really are game changing. Most of my types are variant types
Re:Switching from C++ to Rust by blub on Tuesday March 14, 2023 @01:07PM (#35154723)
Most of your types? Well that certainly deserves congratulations and I hope someone will take advantage of the opportunity.

I think you misunderstood me though if you say I haven’t used them properly. I just didn’t need them or find them that useful because it rarely happens that I want to model a type which has several states.

Specific variant types like std::optional or the Result-equivalents are useful, but not that game changing either. They’re nice I suppose.

I wonder what kind of software you write that such low-level coding idioms make a big difference to the end result. Or what do you mean by game changing?

Re:Switching from C++ to Rust by dureuill on Tuesday March 14, 2023 @05:20AM (#35148995)
> Variant types where one has to use objects as types don’t come up that often in API design or data structures in my experience with mobile and system programming on e.g. Linux

You can't use what you don't have, so you adapt to the tools you do have. In my C++ time, the team would often write types that logically held several variants. However they were expressed as product types, so with space overhead and error-prone, unergonomic use.

Sum types are game-changing. Look at any Rust project you'll find enums with data everywhere. They're just a building block to model problems, like product types are. A language that miss them is as strange too me as a language without product types. After 10 years of mostly C++11 and C++14 I would never go back to it for this reason alone (although as outlined in the article there are other reasons too).

> Error types are probably the most popular incarnation of that. There’s several libraries available and they will be part of the C++ standard.

Again, with what performance and ergonomics?

Re:Switching from C++ to Rust by FpUser on Tuesday March 14, 2023 @08:42AM (#35150538)
not to diminish value of sum types (those are not specific to Rust of course) but I think that product types belong to a database / config rather than being hardcoded.
Re:Switching from C++ to Rust by blub on Saturday March 18, 2023 @12:46PM (#35210643)
I just checked the old Rust classic “ripgrep” on github.

In matcher.rs, the enum is used as poor man’s OOP. I saw several match expressions which then call the same function on each matched type.

searcher/mod.rs is an error definition.

glob.rs contains a sort of policy enum which can be implemented once again with OOP or as a policy template.

json.rs usage can be modeled as a single class.

core/app.rs is more involved, but can be modeled as a series of structs with a map from enum -> any. Or as am std::variant. Or using OOP.

I looked at all instances and didn’t see anything game-changing. It’s a nice syntax and it should have really good performance, but such idioms are way too low-level to change any game.

Re:Switching from C++ to Rust by burntsushi on Saturday March 25, 2023 @03:17PM (#35306070)
This is a straw man. There is nobody on this Earth claiming that sum types are necessary to solve a problem. Product types aren't necessary either. You could just write everything in Assembly. Or maybe raw bytecode if you want.

As should be patently fucking obvious to anyone who has been commenting on a technology web site for as long as you have, sum types are a tool. They are a tool for expressing clearly and concisely the idea that a value can be exactly one of several possible options. That tool then interacts with the rest of the language based on that invariant, sometimes providing things like exhaustiveness checking and pattern matching. Put all this together, and you have a very succinct and very clear way of representing certain kinds of values in a program.

Your comment might as well go through ripgrep and talk about how functions aren't needed. "They could have just used goto here and there."

> I looked at all instances and didn’t see anything game-changing. It’s a nice syntax and it should have really good performance, but such idioms are way too low-level to change any game.

Sum types were game changing to me when I learned about them over a decade ago. Since then, they have been a significant factor in how I think about and structure data in programs.

I have zero interest in trying to convince someone like you that you should think it's game changing. That's not the point. Maybe you could do some perspective taking and realize that others might just think differently than you.

Re:Switching from C++ to Rust by whyever on Tuesday March 14, 2023 @05:26AM (#35149035)
I disagree. Whenever there is a null pointer in the API, you could (and probably should) be using a sum type instead.

Sum types are not novel (Standard ML had them 40 years ago), but I think they are indeed a game changer.

Re:Switching from C++ to Rust by blub on Saturday March 18, 2023 @12:59PM (#35210813)
You’ve described std::optional, a special case of std::variant.
Re:Switching from C++ to Rust by JonChesterfield on Tuesday March 14, 2023 @11:39AM (#35153294)
> This is a case of the Rust community overselling a minor feature as a game-changing novelty.

Sum types reify control flow into an object from which said control flow can be retrieved. Compiler checked sum types remove the possibility of retrieving inconsistent control flow.

The transform is equivalent to callback to future.

It's one of the things that looks unimportant until you use it. After that, the absence is extremely apparent when working with C++. We don't use tagged unions much because the ergonomics are terrible.

Re:Switching from C++ to Rust by tialaramex on Tuesday March 14, 2023 @05:17AM (#35148977)
So, so many ways in which this is defective compared to actual sum types, some of them were already listed, but to me the most crucial, even if mostly about theory rather than practice, is valueless_by_exception.

The choice to provide exceptions everywhere as a error handling means C++ is obliged to admit that your std::variant may not have a value at all. Which blows up all of your type safety. In Rust I can say that this Pet is either a Dog or a Cat, and it cannot be neither, but in C++ std::variant of a Cat and a Dog might nevertheless be valueless_by_exception anyway. What can you do about that? I guess you could throw an exception...

In Rust if X is either A or B, and Y is either C or D, and Z is either E or F, then a structure with X, Y and Z has only eight possible states. In C++ this structure has 27 possible states because of exceptions.

Re:Switching from C++ to Rust by dureuill on Tuesday March 14, 2023 @05:30AM (#35149061)
I get the "theoretical" point, but the issues I encountered in practice are closer to the ones I listed in my response than to valueless_by_exception (which I never encountered, I think?).

Wrt type safety we had more pressing issues with C++ (use after move, implicit conversions, ...)

Re:Switching from C++ to Rust by planede on Tuesday March 14, 2023 @07:14AM (#35149737)
Exceptions are an optional feature. Also, if sufficient amount of constructors are marked noexcept, then the variant can never be valueless. Implementations are optimized accordingly.

You also don't have to handle the exception, in which case you won't access the variant again anyway. Or it gets handled where the variant is teared down. It's very unlikely that it gets handled where the variant is constructed or assigned to, making it a non-issue.

Re:Switching from C++ to Rust by pjmlp on Tuesday March 14, 2023 @09:58AM (#35151615)
They aren't as per ISO C++, even though all compilers allow to disable them in non standard conforming ways.
Re:Switching from C++ to Rust by planede on Tuesday March 14, 2023 @11:40AM (#35153309)
I meant exceptions as a user of the language. You can decide not to throw. You can mark functions noexcept.

Granted, it's more awkward when you consume 3rd party libraries, but you can still wrap them in noexcept interfaces and be fine with terminating when an exception is actually thrown or do something else. Not much different to a panic.

Re:Switching from C++ to Rust by MathMonkeyMan on Monday March 13, 2023 @09:53PM (#35146295)
Until very recently, all of the C++ code I wrote was in the 1998 style or in the 2014 style.

Since 2017, there is std::variant, which is a sum type template that _technically_ allows for language-level exhaustiveness checking via std::visit. It's not pretty, but it gets you there without requiring compiler support.

Rust's version looks way better.

Re:Switching from C++ to Rust by otabdeveloper4 on Tuesday March 14, 2023 @01:54AM (#35147887)
boost::variant has been around forever.

Most modern C++ codebases do compile-time polymorphism via templates, though. std::variant is a niche use for things like serialization, when you need to make type choices at runtime.

Re:Switching from C++ to Rust by chippiewill on Tuesday March 14, 2023 @08:27AM (#35150381)
I was really excited for `std::variant`, when I actually got it I was seriously disappointed.

It's just a pain to use because of how much template magic is used.

Re:Switching from C++ to Rust by rayiner on Monday March 13, 2023 @11:16PM (#35146956)
A nice thing about Rust is that it brings many well established good ideas from the ML branch of languages to the curly brave branch of languages. And frankly does a better job naming them (for people who weren’t math majors).
Re:Switching from C++ to Rust by chippiewill on Tuesday March 14, 2023 @08:23AM (#35150316)
A monad is just a monoid in the category of endofunctors.

Seriously though, calling Algebraic Data Types an Enum was a stroke of genius.

Re:Switching from C++ to Rust by japanuspus on Tuesday March 14, 2023 @09:27AM (#35151125)
Completely agree. This article [0] by Raphael Poss, explicitly listing how functional constructs look in Rust compared with "pure" functional languages is one of my favorite takes on Rust.

[0]: https://dr-knz.net/rust-for-functional-programmers.html

Re:Switching from C++ to Rust by the_gipsy on Tuesday March 14, 2023 @03:30AM (#35148363)
Same here, go would be such a killer language if it just had sum types.
Re:Switching from C++ to Rust by kaba0 on Tuesday March 14, 2023 @05:29AM (#35149055)
Yeah, it might even reach Java 1.1, feature-wise then.
Re:Switching from C++ to Rust by the_gipsy on Tuesday March 14, 2023 @06:25AM (#35149437)
Java does not have sum types.
Re:Switching from C++ to Rust by kaba0 on Tuesday March 14, 2023 @06:34AM (#35149477)
It didn’t have at 1.1, but it does now: https://news.ycombinator.com/item?id=35133670
Re:Switching from C++ to Rust by the_gipsy on Tuesday March 14, 2023 @07:06AM (#35149677)
You can do that with go too, there are libraries out there. But it's all a joke compared to real support in the language.
Re:Switching from C++ to Rust by kaba0 on Tuesday March 14, 2023 @07:13AM (#35149732)
Real support like what Java has? It literally has sealed classes and interfaces that specify all the possible classes that can subtype it. This is enforced by the language and allows for things like exhaustive switch cases. Pattern matching is a related feature which is also available in Java now, though as of yet only limited to records.
Re:Switching from C++ to Rust by the_gipsy on Tuesday March 14, 2023 @07:36AM (#35149918)
So it's a Frankenstein monster, with no real pattern matching support. Good luck with using it in the real world.
Re:Switching from C++ to Rust by ptman on Tuesday March 14, 2023 @05:41AM (#35149151)
Go generics allow all kinds of things https://github.com/samber/mo
Re:Switching from C++ to Rust by burntsushi on Tuesday March 14, 2023 @07:35AM (#35149907)
I'm aware. I wrote go-sumtype long before Go got generics.
Re:Switching from C++ to Rust by endorphine on Tuesday March 14, 2023 @06:27AM (#35149451)
Can someone elaborate on what sum types are and an example in Rust?
Re:Switching from C++ to Rust by burntsushi on Tuesday March 14, 2023 @07:34AM (#35149899)
The section on "enums and pattern matching" in the Rust book is probably a good place to start: https://doc.rust-lang.org/book/ch06-00-enums.html

A "Rust enum" is a sum type.

Re:Switching from C++ to Rust by endorphine on Thursday March 16, 2023 @01:35PM (#35185272)
Are there other examples of sum types besides enums, in Rust? Are the two terms synonymous?
Re:Switching from C++ to Rust by steveklabnik on Thursday March 16, 2023 @02:28PM (#35186181)
Rust does not have sum types outside of enums. Other languages have sum types, and may or may not call them enums depending on the language.
Re:Switching from C++ to Rust by PaulHoule on Wednesday March 15, 2023 @10:05AM (#35168509)
… or sealed classes in Java