More on Rust

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Feb 10 11:49:49 PST 2011


On 2/10/11, Walter Bright <newshound2 at digitalmars.com> wrote:
> auto x = (localtime().hours >= 8) ? "awake!" : "asleep, go away.";

Aye, a one liner!

I hate seeing things like this:
if (funcall())
{
    var = "foo";
}
else
{
    var = "bar";
}

So much clutter instead of using the simple:
var = funcall() ? "foo" : "bar";

I also see this sometimes:

auto var = funcall();
if (var == "foo" || var == "bar" || var == "foobar" || var == "barfoo")
{
    // some complex code
}
else if (var == "blue" || var == "green")
{
    // some complex code
}
else if ()// more and more code..
{ }

But not many people seem to know that D supports strings in case statements:
switch(funcall())
{
    case "foo":
    case "bar":
    case "foobar":
    case "barfoo":
    {
        // complex code
    }
    break;
    case "blue":
    case "green":
    {
       // complex code
    }
    break;
    default:
}

Not everybody will like this since it wastes a lot of vertical space.
But at least it fits in 80 columns! (:p). Plus you don't need to
create a temporary variable.

The cool thing is the compiler will warn you if you miss out setting
the default switch, which is something you won't get with if/elseif's.

The final switch statement is even better when using enums. Added
another enum member, but forgot to update the final switch statement?
Boom, compiler error!

It's a great thing for avoiding bugs imo.


More information about the Digitalmars-d mailing list