What is the most idiomatic way to concatenate integer variables?

我的梦境 提交于 2019-12-23 15:24:07

问题


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


来源:https://stackoverflow.com/questions/27965471/what-is-the-most-idiomatic-way-to-concatenate-integer-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!