Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was reading through the Rust documentation and came across the following example and statement

Using a return as the last line of a function works, but is considered poor style:

fn foo(x: i32) -> i32 {
    if x < 5 { return x; }

    return x + 1;
}

I know I could have written the above as

fn foo(x: i32) -> i32 {
    if x < 5 { return x; }

    x + 1
}

but I am more tempted to write the former, as that is more intuitive. I do understand that the function return value should be used as an expression so the later works but then why wouldn't the former be encouraged?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
750 views
Welcome To Ask or Share your Answers For Others

1 Answer

It just is.

Conventions don’t need to have particularly good reasons, they just need to be generally accepted conventions. As it happens, this one does have a comparatively good reason—it’s shorter as you don’t have the return and ;. You may think that return x + 1; is more intuitive, but I disagree strongly—it really grates and I feel a compelling need to fix it. I say this as one who, before starting using Rust, had never used an expression-oriented language before. While writing Python, return x + 1 in that place looks right, while writing Rust it looks wrong.

Now as it happens, that code should probably be written thus instead:

fn foo(x: i32) -> i32 {
    if x < 5 {
        x
    } else {
        x + 1
    }
}

This emphasises the expression orientation of the language.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...