运行rustfmt遇‘不稳定特性仅在nightly通道可用’警告如何解决?
问题背景
已将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
通过以下命令安装nightly版rustfmt:
rustup toolchain add nightly && rustup component add rustfmt --toolchain nightly
工具链反馈为nightly-x86_64-unknown-linux-gnu unchanged - rustc 1.65.0-nightly (015a824f2 2022-08-22),但执行格式化命令时:
cargo +nightly fmt cargo fmt --check
出现多条特性不可用的警告:
Warning: can't set
imports_granularity = Crate, unstable features are only available in nightly channel.
Warning: can't setreorder_impl_items = false, unstable features are only available in nightly channel.
Warning: can't setspaces_around_ranges = false, unstable features are only available in nightly channel.
Warning: can't setbinop_separator = Back, unstable features are only available in nightly channel.
Warning: can't setmatch_arm_blocks = false, unstable features are only available in nightly channel.
Warning: can't settrailing_semicolon = false, unstable features are only available in nightly channel.
Warning: can't settrailing_comma = Vertical, unstable features are only available in nightly channel.
问题原因
你使用的imports_granularity、reorder_impl_items等配置属于rustfmt的不稳定特性,即使安装了nightly版rustfmt,默认也不会启用这些特性,必须显式声明开启。另外,cargo fmt --check默认调用stable版rustfmt,本身不支持这些特性,因此也会触发警告。
解决步骤
- 启用不稳定特性
在.rustfmt.toml文件最顶部添加如下配置:
# 开启rustfmt不稳定特性支持 unstable_features = true
- 统一使用nightly工具链运行格式化
后续执行格式化或检查命令时,必须指定nightly工具链,避免调用stable版:
# 格式化代码 cargo +nightly fmt # 检查代码格式 cargo +nightly fmt --check
补充说明
如果后续Rust stable版将这些特性纳入稳定支持,你可以移除unstable_features = true配置,改用cargo fmt和cargo fmt --check命令即可。
内容的提问来源于stack exchange,提问作者Russo

