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

Rust中如何让rustfmt生效格式化文档测试(doctest)代码?

问题

在Rust项目中,文档注释内的doctest代码格式混乱(缩进错误),示例如下:

//!   
//! example:
//!  
//!```
//! 
//!         use nalgebra::{Quaternion, UnitQuaternion, Vector3};
//! // use crate::naive_cf::NaiveCF;
//! 
//! let acc = Vector3::new(3.64637947, 5.30298471, 6.84866046);
//! 
//!         let rotation = UnitQuaternion::from_quaternion(Quaternion::new(
//!             0.60163784,
//!             -0.0844770521,
//!            0.269781291,
//!            -0.614157497,
//!        ));
//! 
//! let v = NaiveCF::new();
//!        // let v = NaiveCF::get_correction_verified(&acc, &rotation);
//! ```

use crate::{ARGlasses, Error, Fusion, GlassesEvent};
use nalgebra::{Quaternion, UnitQuaternion, Vector3};

// ...

已在rustfmt配置中设置了如下参数:

format_code_in_doc_comments = true
format_macro_matchers = true
group_imports = "StdExternalCrate"
hex_literal_case = "Lower"
imports_granularity = "Module"
newline_style = "Unix"
normalize_comments = true
normalize_doc_attributes = true
use_field_init_shorthand = true
use_try_shorthand = true

执行cargo fmt后,文档测试代码仍未被格式化,请问该如何正确配置让rustfmt对doctest代码生效?

解决方案
  • 修正代码块标记:rustfmt仅会格式化标注为rust的代码块,你的doctest代码块仅写了//!````,需要改为//!```rust`,明确指定代码语言。
  • 更新rustfmt版本:旧版rustfmt对文档注释内代码的格式化支持存在缺陷,运行rustfmt --version检查版本,确保使用与当前Rust稳定版匹配的最新版本,可通过rustup update更新工具链。
  • 验证配置生效状态:执行cargo fmt --print-config current查看当前生效的rustfmt配置,确认format_code_in_doc_comments确实被设置为true,同时确保配置文件(rustfmt.toml或.rustfmt.toml)放在项目根目录,未被局部配置覆盖。
  • 指定文件格式化:若项目文件较多,可尝试直接指定目标文件执行格式化,命令示例:cargo fmt -- src/your_target_file.rs,确保目标文件被rustfmt处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:13:14