保留语法
概述
- 形如
#"foo"#
的无前缀保护字符串被保留供将来使用。 - 两个或更多
#
字符被保留供将来使用。
详情
RFC 3593 在 2024 版本中为无前缀的保护字符串字面量保留了语法,以便为未来可能的语言变更留出空间。2021 版本 保留了语法 用于带有前缀的保护字符串,例如 ident##"foo"##
。2024 版本扩展了这一点,也保留了没有 ident
前缀的字符串。
有两种保留语法
- 一个或多个
#
字符紧随其后的 字符串字面量。 - 两个或更多
#
字符连续出现(没有空格分隔)。
这种保留跨版本边界进行,因为涉及到分词和宏的交互。例如,考虑以下宏
#![allow(unused)] fn main() { macro_rules! demo { ( $a:tt ) => { println!("one token") }; ( $a:tt $b:tt $c:tt ) => { println!("three tokens") }; } demo!("foo"); demo!(r#"foo"#); demo!(#"foo"#); demo!(###) }
在 2024 版本之前,这将产生
one token
one token
three tokens
three tokens
从 2024 版本开始,#"foo"#
行和 ###
行现在会生成编译错误,因为这些形式现在已被保留。
迁移
rust_2024_guarded_string_incompatible_syntax
lint 将识别任何匹配保留语法的 token,并将建议进行修改,在必要时插入空格,以确保 token 继续被单独解析。
该 lint 是 rust-2024-compatibility
lint 组的一部分,该组包含在自动版本迁移中。为了迁移您的代码以兼容 Rust 2024 版本,请运行
cargo fix --edition
或者,您可以手动启用该 lint 以查找您可能需要更新 token 的宏调用
#![allow(unused)] fn main() { // Add this to the root of your crate to do a manual migration. #![warn(rust_2024_guarded_string_incompatible_syntax)] }