What is the most idiomatic way to concatenate inte

2019-06-26 09:26发布

问题:

The compiler doesn't seem to infer that the integer variables are passed as string literals into the concat! macro, so I found the stringify! macro that converts these integer variables into string literals, but this looks ugly:

fn date(year: u8, month: u8, day: u8) -> String
{
    concat!(stringify!(month), "/",
            stringify!(day), "/",
            stringify!(year)).to_string()
}

回答1:

concat! takes literals and produces a &'static str at compile time. You should use format! for this:

fn date(year: u8, month: u8, day: u8) -> String {
    format!("{}/{}/{}", month, day, year)
}


回答2:

Also note that your example does not do what you want! When you compile it, you get these warnings:

<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
                                      ^~~

Note that all the variables are unused! The output of calling the function will always be the string:

month/day/year