#Is there a cleaner way to rewrite this?

1 messages · Page 1 of 1 (latest)

pure trail
#
const c = blk: {
    if (a > b) {
        // some processes
        break :blk 100;
    } else {
        // some processes
        break :blk 200;
    }
};

In rust, if is an expression which can direct return the final value.

But in Zig, what I can do is:

var c: i32 = undefined;
if (a > b) {
    // some processes
    c = 100;
} else {
    // some processes
    c = 200;
}

Either I have to change const to var, or I can do is using a block with an additional label and break value to it.

Is there a better way to rewrite this?

tired canyon
#

if you remove the braces you don't need the break

#

const c = if (a > b) 100 else 200;

pure trail
tired canyon
#

oh sorry didn't see that

#

then no this is kinda the way

#

I would definitely not do the second one tho with var

pure trail
tired canyon
#

not sure I agree

#

you can also remove the outer block and instead label the if/else blocks individually and break from those

pure trail
tired canyon
#

if (...) blk: {} else blk: {}

#

it's not anything special to if/else it's just labeling a block

pure trail
#

I just noticed that I can use _: as a label, which has much less noise than blk:.

#
const c = _: {
    if (a > b) {
        // some processes
        break :_ 100;
    } else {
        // some processes
        break :_ 200;
    }
};

It's a little cleaner now.

wintry yacht
#
const num_foos = num_foos: {
    var n: usize = 0;
    ...
    break :num_foos n;
};
crimson oasis
#

Yeah, I'm a proponent of naming blocks that way

austere harness
#

I got used to appending _calc idk why... like variablename_calc:

spark copper