连接整数变量的最惯用方式是什么? [英] What is the most idiomatic way to concatenate integer variables?

查看:52
本文介绍了连接整数变量的最惯用方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器似乎没有推断出整数变量是作为字符串文字传递给 concat!宏的,所以我发现了 stringify !宏,将这些整数变量转换为字符串文字,但这看起来很难看:

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()
}


推荐答案

concat!接受文字并在 compile 时生成&'static str 。您应该使用格式!

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)
}

这篇关于连接整数变量的最惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆