编译器似乎没有推断整数变量作为字符串文字传递到concat!
宏,所以我发现stringify!
宏将这些整数变量转换为字符串文字,但是这个看起来很难看:
fn date(year: u8, month: u8, day: u8) -> String
{
concat!(stringify!(month), "/",
stringify!(day), "/",
stringify!(year)).to_string()
}
答案 0 :(得分:10)
concat!
需要文字并在编译时生成&'static str
。您应该使用format!
:
fn date(year: u8, month: u8, day: u8) -> String {
format!("{}/{}/{}", month, day, year)
}
答案 1 :(得分:4)
另请注意,您的示例不符合您的要求!编译时,会收到以下警告:
<anon>:1:9: 1:13 warning: unused variable: `year`, #[warn(unused_variables)] on by default
<anon>:1 fn date(year: u8, month: u8, day: u8) -> String
^~~~
<anon>:1:19: 1:24 warning: unused variable: `month`, #[warn(unused_variables)] on by default
<anon>:1 fn date(year: u8, month: u8, day: u8) -> String
^~~~~
<anon>:1:30: 1:33 warning: unused variable: `day`, #[warn(unused_variables)] on by default
<anon>:1 fn date(year: u8, month: u8, day: u8) -> String
^~~
请注意,所有变量都未使用!调用该函数的输出将始终为字符串:
month/day/year