News for hackers. Stuff that matters.
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.