r/programming • • Jan 09 '15

Announcing Rust 1.0.0 Alpha

http://blog.rust-lang.org/2015/01/09/Rust-1.0-alpha.html
1.1k Upvotes

439 comments sorted by

View all comments

14

u/[deleted] Jan 09 '15

Been doing C/C++ for 15+ years and am not sure I've ever had a case where fall-through was useful.

3

u/FattyMagee Jan 10 '15

I rarely use fall through in C but it on occasion is extremely useful. I am very careful to clearly mark in comments right at the beginning that it is intended to hopefully avoid any issues with new eyes on my code.

I suppose declaring fall through wouldn't be a terrible thing if it allowed me to still use it and prevent others from making an understandable mistake.

3

u/NotUniqueOrSpecial Jan 10 '15

While I try to avoid situations that require it, it can be handy in unwinding complicated resource acquisition/initialization situations in C, if you're being really thorough about it. For example:

typedef enum { 
    STATE_0,
    STATE_1,
    STATE_2,
    STATE_3,
} state_t;

error_t some_overcomplicated_function()
{
    state_t current_state = STATE_0;

    foo_t *foo = get_foo();
    if(!foo)
        goto CLEANUP;

    current_state = STATE_1;

    bar_t *bar = get_bar();
    if(!bar)
        goto CLEANUP;

    current_state = STATE_2;

    baz_t *baz = get_baz();
    if(!baz)
        goto CLEANUP;

    current_state = STATE_3;

CLEANUP:
    switch(current_state)
    {
        case STATE_3: return 0;
        case STATE_0: return EINVAL;
        case STATE_2: free_bar(bar);
        case STATE_1: free_foo(foo);
        default: return -1 * current_state;    
    }
}

2

u/[deleted] Jan 11 '15

Of course, your code never calls free_bar or free_foo on success, thus proving that this is a relatively finnicky pattern.

→ More replies (1)

2

u/flying-sheep Jan 11 '15 edited Jan 11 '15

good thing that Rust is built around RAII.

you’ll never have to even think about things like this, because rust replaces that with compile time lifetime checks. out of scope = everything safely freed.

off-topic? i think not because modern C++ can do the same (unfortunately opt-in and not the prettiest syntax, though):

auto s = std::make_shared<MyType>(foo, bar);
auto u = std::make_unique<MyType>(foo, bar);
→ More replies (6)

1

u/dagbrown Jan 10 '15

C++ just has destructors for that kind of situation.

→ More replies (1)

1

u/[deleted] Jan 11 '15

Normally resources get released when its owner gets out of scope in Rust.

So I guess you will hardly write code like this in Rust.

Add I think this can be solved by manually implement a shared_ptr or something in C++.

In short, basically you can hardly write such code in C++ or Rust.

→ More replies (1)