You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免rustfmt将含trivial表达式的else代码块格式化为多行?

How to Keep Trivial else Blocks Single-Line with Rustfmt (When single_line_if_else_maxwidth Fails)

Great question! I’ve struggled with this exact Rustfmt behavior before—when the if branch has long, multi-line code, Rustfmt tends to split even trivial else blocks onto multiple lines, even though you want them compact like else { None }. Since single_line_if_else_maxwidth only works when the entire if-else fits within the specified width (which it won’t here, thanks to your long if block), here are your best solutions:

1. Locally Disable Rustfmt for the if-else Statement

The most targeted fix is to tell Rustfmt to ignore just this specific if-else using a comment or attribute. This keeps your long if branch properly formatted while preserving the compact else block.

Using // rustfmt-ignore

Add this comment directly above the if statement:

// rustfmt-ignore
if condition {
    // code that deserves to
    // be formatted as block
} else { None }

Using #[rustfmt::skip] Attribute

If you’re assigning the result to a variable, you can apply the attribute to the entire statement:

#[rustfmt::skip]
let value = if condition {
    // code that deserves to
    // be formatted as block
} else { None };

This makes it clear exactly which code you’re opting out of formatting, and avoids accidentally ignoring surrounding code.

2. Adjust Rustfmt’s Global Configuration

If you want this behavior to apply project-wide (for all trivial single-line else blocks), you can modify your rustfmt.toml file. Add the following line:

keep_single_line_blocks = true

This tells Rustfmt to retain single-line blocks (like { None }) as-is, instead of splitting them into multi-line blocks. Note that this will affect all similar blocks in your codebase, so make sure it aligns with your team’s formatting preferences.

3. Refactor for Implicit Return (Optional)

If your if block is the last expression in a function, you can omit the curly braces for the else branch entirely (though this is a stylistic choice):

fn example(condition: bool) -> Option<()> {
    if condition {
        // code that deserves to
        // be formatted as block
        Some(())
    } else {
        None
    }
    // Or, more compact:
    if condition {
        // code that deserves to
        // be formatted as block
        Some(())
    } else None
}

This avoids the curly braces altogether, but it’s a matter of personal taste—some teams prefer explicit braces even for trivial expressions.

Each approach has its tradeoffs: local disabling gives you precise control, global configuration enforces consistency, and refactoring changes the syntax slightly. Pick the one that fits your project’s needs best!

内容的提问来源于stack exchange,提问作者Ingo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:47:47