What is the most idiomatic way to concatenate integer variables?

The compiler does not think that integer variables are passed as string literals to a macro concat!, so I found a macro stringify!that converts these integer variables to string literals, but it looks ugly:

fn date(year: u8, month: u8, day: u8) -> String
{
    concat!(stringify!(month), "/",
            stringify!(day), "/",
            stringify!(year)).to_string()
}
+4
source share
2 answers

concat!takes literals and creates time &'static strat compile time. You should use format!for this:

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

Also note that your example does not do what you want ! When you compile it, you will receive the following 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
                                      ^~~

, ! :

month/day/year
+4

All Articles