Clippy tells me to remove return keyword but then the compiler errors

I have a function that returns a formatted string...

fn format_str(base: &str, path: &str) -> String {
    return !format("{}{}", base, path);
}

This works great, but when I run clippy it warns me to remove the return statement, which I would typically do but in this case the compiler throws and thinks I am returning () when it should be String

mismatched types expected String, found ()

I guess because this is a macro. But who is wrong here? I think clippy is being a bit overzealous but maybe I am missing something. Seems like clippy should not be suggesting breaking the build.

I assume you mean

    return format!("{}{}", base, path);

The suggested change is:

fn format_str(base: &str, path: &str) -> String {
    format!("{}{}", base, path)  // <--- no ';'!
}

Many blocks in Rust, including function bodies, evaluate to the value of their trailing expression, or () if there is no trailing expression. You have to remove the ; to turn the statement into a trailing expression.

3 Likes

Wow thanks. The semicolon indeed was the problem. I blindly followed the instructions to remove the return and left the semicolon. You can tell I am only in week 1 of rust :slight_smile:

For future reference, it's a good idea to read warnings carefully and not only get the idea of what's going on - in this case, in particular, Clippy provided the exact replacement string, with both return and semicolon removed (and if this suggestion ends up misleading, that's actually a bug, and we'd like to know what to fix).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.