为什么concat! 宏对const变量不起作用?
由于 const 变量在编译时就会被求值,为什么在使用 concat! 宏将多个 const &str 变量拼接时,不能使用它们?
我参考了这份 指南,因为它说可以使用 concat! 宏将 const 变量拼接在一起。但当我尝试编译下面的代码时,编译失败了:
const APP_NAME: &str = "MyApp";
const APP_MAJOR: u8 = 1;
const APP_MINOR: u8 = 2;
fn main() {
let version = concat!(APP_NAME, " v", APP_MAJOR, ".", APP_MINOR);
println!("{}", version); // Output: MyApp v1.2
}
错误:
error: expected a literal
--> src/main.rs:6:27
|
6 | let version = concat!(APP_NAME, " v", APP_MAJOR, ".", APP_MINOR);
| ^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^
|
= note: only literals (like `"foo"`, `-42` and `3.14`) can be passed to `concat!()`
解决方案
concat! 是一个内置宏,它只接受原始字符串字面量,因为它是代码生成的一部分,在编译的初始阶段就会展开,早于类型解析/所有权检查等。对于常量变量的编译时拼接,你可以使用 const_format:
use const_format::concatcp;
const APP_NAME: &str = "MyApp";
const APP_MAJOR: u8 = 1;
const APP_MINOR: u8 = 2;
fn main() {
let version = concatcp!(APP_NAME, " v", APP_MAJOR, ".", APP_MINOR);
println!("{}", version); // Output: MyApp v1.2
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。