rustfmt.toml 配置 ​

核心概念 ​

rustfmt 是 Rust 官方的代码格式化工具,通过 cargo fmt 命令自动格式化项目中所有 Rust 源文件。rustfmt 遵循 Rust 社区统一的代码风格规范,保证团队成员写出风格一致的代码。

rustfmt.toml(或 .rustfmt.toml)是 rustfmt 的配置文件,放在项目根目录。通过它可以调整缩进宽度、行宽限制、导入排序等格式化行为。大部分配置项在 stable 版本中不可用(标记为 unstable),需要 nightly 工具链。

bash
# 格式化当前项目
# cargo fmt

# 检查格式但不修改(CI 中常用)
# cargo fmt -- --check

# 格式化特定文件
# rustfmt src/main.rs

# 使用 nightly 格式化(启用不稳定选项)
# cargo +nightly fmt

常用配置项 ​

toml
# rustfmt.toml

# === 稳定版可用的配置 ===

# 最大行宽(默认 100)
max_width = 100

# 使用硬制表符还是空格(默认 false,即用空格)
hard_tabs = false

# 缩进宽度(默认 4)
tab_spaces = 4

# edition(与 Cargo.toml 中保持一致)
edition = "2024"

# 使用字段初始化简写 { x } 代替 { x: x }
use_field_init_shorthand = true

# 合并导入(use std::io::{self, Read})
# 默认值:Preserve
imports_granularity = "Crate"    # nightly

# 导入排序
# reorder_imports = true          # 默认 true

稳定版配置项 ​

配置项默认值说明
max_width100最大行宽
hard_tabsfalse是否用制表符
tab_spaces4缩进空格数
edition"2015"Rust edition
use_field_init_shorthandfalse字段初始化简写
use_try_shorthandfalse用 ? 替代 try!
newline_style"Auto"换行风格(Auto/Unix/Windows)

Nightly 配置项 ​

toml
# 以下配置需要 nightly 工具链
# cargo +nightly fmt

# 导入合并粒度
imports_granularity = "Crate"
# "Preserve" — 保持原样
# "Crate"    — 按 crate 合并
# "Module"   — 按模块合并
# "Item"     — 每项单独一行

# 导入排序
group_imports = "StdExternalCrate"
# "Preserve"          — 保持原样
# "StdExternalCrate"  — 标准库、外部crate、本地crate 分组

# 函数参数排版
fn_params_layout = "Tall"
# "Compressed" — 尽量放一行
# "Tall"       — 每个参数一行
# "Vertical"   — 全部垂直排列

# 注释宽度
comment_width = 80
wrap_comments = true

# 匹配臂末尾逗号
match_arm_blocks = true

# 结构体字面量中的尾随逗号
trailing_comma = "Vertical"

# 链式调用缩进
chain_width = 60

# 单行表达式最大宽度
single_line_if_else_max_width = 50

格式化控制 ​

rust
// 在代码中控制格式化行为

// 跳过格式化某个模块
#[rustfmt::skip]
mod ugly_but_intentional {
    fn intentionally_formatted(  ) -> i32 {
        42
    }
}

// 跳过格式化某个函数
#[rustfmt::skip]
fn matrix() -> [[i32; 3]; 3] {
    [
        [1, 0, 0],
        [0, 1, 0],
        [0, 0, 1],
    ]
}

// 跳过格式化某个表达式
fn formatted_function() {
    let normal = vec![1, 2, 3];

    #[rustfmt::skip]
    let aligned = vec![
        1,   2,   3,
        10,  20,  30,
        100, 200, 300,
    ];

    println!("{:?}", normal);
    println!("{:?}", aligned);
}

fn main() {
    formatted_function();
}

基本示例 ​

toml
# 一个实际项目的 rustfmt.toml 配置

# 基本格式
max_width = 100
tab_spaces = 4
hard_tabs = false
edition = "2024"
newline_style = "Unix"

# 简写
use_field_init_shorthand = true
use_try_shorthand = true

# 以下需要 nightly
# imports_granularity = "Crate"
# group_imports = "StdExternalCrate"
# wrap_comments = true
# comment_width = 80
rust
// 格式化前
use std::collections::HashMap;use std::io::{self,Read};
fn main(){let mut map=HashMap::new();map.insert("key","value");println!("{:?}",map);}

// 格式化后(cargo fmt)
use std::collections::HashMap;
use std::io::{self, Read};

fn main() {
    let mut map = HashMap::new();
    map.insert("key", "value");
    println!("{:?}", map);
}
rust
// 实际项目中的格式化效果

use std::collections::HashMap;

pub struct Config {
    name: String,
    values: HashMap<String, String>,
}

impl Config {
    pub fn new(name: &str) -> Self {
        Config {
            name: name.to_string(),
            values: HashMap::new(),
        }
    }

    pub fn set(&mut self, key: &str, value: &str) {
        self.values.insert(key.to_string(), value.to_string());
    }

    pub fn get(&self, key: &str) -> Option<&String> {
        self.values.get(key)
    }
}

fn main() {
    let mut config = Config::new("app");
    config.set("host", "localhost");
    config.set("port", "8080");

    if let Some(host) = config.get("host") {
        println!("host = {}", host);
    }
}

常见问题 ​

问题一:rustfmt.toml 和 .rustfmt.toml 有什么区别?

没有区别,两种文件名都可以。rustfmt 会按顺序查找:当前目录的 rustfmt.toml → .rustfmt.toml → 父目录,一直到根目录。

问题二:怎么在 CI 中检查格式?

用 cargo fmt -- --check。如果有未格式化的代码,命令返回非零退出码,CI 构建失败。

问题三:unstable 选项怎么使用?

在 rustfmt.toml 顶部加 unstable_features = true(某些版本需要),然后用 cargo +nightly fmt 运行。或者在配置中直接使用不稳定选项。

问题四:可以关闭 rustfmt 对某些文件的格式化吗?

可以。在文件开头加 // rustfmt::skip_all 跳过整个文件(nightly),或者使用 #[rustfmt::skip] 跳过特定项。也可以在 rustfmt.toml 中配置 ignore 列表。

适用场景 ​

  • 团队协作:统一代码风格,减少代码审查中的格式争论
  • CI/CD:自动检查格式一致性
  • 开源项目:贡献者遵循统一的代码风格
  • IDE 集成:保存时自动格式化

注意事项 ​

  • cargo fmt -- --check 用于 CI 检查
  • 大部分高级配置项需要 nightly 工具链
  • #[rustfmt::skip] 跳过特定代码段的格式化
  • rustfmt.toml 放在项目根目录
  • edition 要与 Cargo.toml 保持一致
  • 不要频繁修改格式配置,避免不必要的 diff

总结 ​

rustfmt 通过 cargo fmt 自动格式化 Rust 代码,rustfmt.toml 配置格式化行为。稳定版的配置项包括 max_width、tab_spaces、hard_tabs、edition 等。高级配置(如 imports_granularity、group_imports)需要 nightly。#[rustfmt::skip] 跳过特定代码的格式化。CI 中用 cargo fmt -- --check 确保代码格式一致。rustfmt 消除了格式争论,让团队专注于代码逻辑。