让 Rustfmt 跳过项目的官方方法是#[rustfmt::skip],但是我希望它跳过整个文件。我试过这个:
#![rustfmt::skip]
Run Code Online (Sandbox Code Playgroud)
但是你得到这个错误
错误[E0658]:非内置内部属性不稳定
有解决方法吗?我不感兴趣的解决方案:
rustfmt.toml例如)我正在尝试使用syn从 Rust 文件创建 AST,然后使用quote将其写入另一个文件。然而,当我写它时,它在所有内容之间放置了额外的空格。
请注意,下面的示例只是为了演示我遇到的最小可重现问题。我意识到,如果我只是想复制代码,我可以复制文件,但它不适合我的情况,我需要使用 AST。
pub fn build_file() {
let current_dir = std::env::current_dir().expect("Unable to get current directory");
let rust_file = std::fs::read_to_string(current_dir.join("src").join("lib.rs")).expect("Unable to read rust file");
let ast = syn::parse_file(&rust_file).expect("Unable to create AST from rust file");
match std::fs::write("src/utils.rs", quote::quote!(#ast).to_string());
}
Run Code Online (Sandbox Code Playgroud)
它创建 AST 的文件是这样的:
#[macro_use]
extern crate foo;
mod test;
fn init(handle: foo::InitHandle) {
handle.add_class::<Test::test>();
}
Run Code Online (Sandbox Code Playgroud)
它输出的内容是这样的:
# [macro_use] extern crate foo ; mod test ; fn init (handle : foo :: InitHandle) { handle . add_class …Run Code Online (Sandbox Code Playgroud) 我在 vscode 上使用 Rust 扩展,而不是 rust-analyzer。但是,当我保存文件时,vscode 使用 rustfmt 来格式化我的文件,但它不会自动插入分号。我有一个像这样的简单功能
fn call_me() {
let x = 5
println!(x)
}
Run Code Online (Sandbox Code Playgroud)
它没有添加必要的分号。如何让它添加分号?我的安装是否有些混乱?
另外,我尝试过 rust-analyzer,它也不添加分号。
我刚刚将 Rust 更新为 rustc 1.63.0 (4b91a6ea7 2022-08-08)
在我的 .rustfmt.toml 文件中
# Basic
hard_tabs = true
max_width = 100
use_small_heuristics = "Max"
# Imports
imports_granularity = "Crate"
reorder_imports = true
# Consistency
newline_style = "Unix"
# Misc
binop_separator = "Back"
chain_width = 80
match_arm_blocks = false
match_arm_leading_pipes = "Preserve"
match_block_trailing_comma = true
reorder_impl_items = false
spaces_around_ranges = false
trailing_comma = "Vertical"
trailing_semicolon = false
use_field_init_shorthand = true
Run Code Online (Sandbox Code Playgroud)
通过 Rust nightly 工具链安装 rustfmt
rustup toolchain add nightly && rustup component add rustfmt …Run Code Online (Sandbox Code Playgroud) rustfmt在 IntelliJ 或 CLion 中保存文件时如何自动运行?
#[rustfmt::skip]允许您在格式化时跳过“代码块”,但这需要skip在每个代码块上{}而不是 Clang 样式on/off
考虑这个代码:
fn add(a : i32, b : i32) -> i32 { a + b }
fn sub(a : i32, b : i32) -> i32 { a - b }
Run Code Online (Sandbox Code Playgroud)
rustfmt 将其格式化为:
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn sub(a: i32, b: i32) -> i32 {
a - b
}
Run Code Online (Sandbox Code Playgroud)
一个需要两个#[rustfmt::skip]属性而不是单个on/off.
单行函数有一个 rustfmt 选项,但此示例仅用于演示目的。我想控制该地区任何可能的 rustfmt 设置。
static TEST: &str = "test: {}";
fn main() {
let string = format!(TEST, "OK");
println!("{}", string);
}
Run Code Online (Sandbox Code Playgroud)
我想构造字符串“test: OK”,但这不起作用。我该怎么做?
某些 IDE 可以帮助实现类型可视化。以下是 VS Code 中的示例(《The Rust 编程语言》书中的示例略有修改):
但其他观众(例如,用于公关评论的观众)则不然。
是否可以以始终使类型显式化的方式设置 Rustfmt?如果没有——还有其他选择吗?
PS:我知道重构会更具挑战性。但我仍然更喜欢优化所有代码查看器的可读性。