For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/rust-code-quality/needless-return.md. A documentation index is available at /llms.txt.

Remove unnecessary explicit return statements

This product is not supported for your selected Datadog site. ().

Metadata

ID: rust-code-quality/needless-return

Language: Rust

Severity: Warning

Category: Code Style

Description

In Rust, a function returns the value of its last expression implicitly — no return keyword is needed. An explicit return at the end of a function body is therefore redundant and adds visual noise without any benefit.

How to remediate?

Remove the return keyword and the trailing semicolon from the last expression:

// Before
fn add(a: i32, b: i32) -> i32 {
    return a + b;
}

// After
fn add(a: i32, b: i32) -> i32 {
    a + b
}

Non-Compliant Code Examples

fn explicit_return() -> i32 {
    return 42;
}

fn explicit_return_expr(x: i32) -> i32 {
    let y = x * 2;
    return y;
}

Compliant Code Examples

fn implicit_return() -> i32 {
    42
}

fn early_return(x: i32) -> i32 {
    if x < 0 {
        return 0; // early exit — not the last statement of the outer block
    }
    x * 2
}

fn cfg_return() -> &'static str {
    #[cfg(unix)]
    return "unix";

    "other"
}

fn with_inner_fn() -> String {
    return helper("foo");

    fn helper(s: &str) -> String {
        s.to_string()
    }
}

fn foo() -> String {
    return s("foo");
    
    fn s(input: &str) -> String {
        input.to_string()
    }    
}

impl Default for LineEnding {
    fn default() -> Self {
        #[cfg(unix)]
        return Self::Unix;

        tracing!("foo")
        Self::Windows
    }
}

fn cfg_return() -> &'static str {
    #[cfg(unix)]
    //
    return "unix";

    "other"
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security