如何在 Rust 中连接静态字符串 [英] How to concatenate static strings in Rust

查看:79
本文介绍了如何在 Rust 中连接静态字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接静态字符串和字符串文字以构建另一个静态字符串.以下是我能想到的最好的方法,但它不起作用:

I'm trying to concatenate static strings and string literals to build another static string. The following is the best I could come up with, but it doesn't work:

const DESCRIPTION: &'static str = "my program";
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const VERSION_STRING: &'static str = concat!(DESCRIPTION, " v", VERSION);

有没有办法在 Rust 中做到这一点,或者我必须一遍又一遍地编写相同的文字?

Is there any way to do that in Rust or do I have to write the same literal over and over again?

推荐答案

由于我本质上是在尝试模拟 C 宏,因此我尝试使用 Rust 宏解决问题并成功:

Since I was essentially trying to emulate C macros, I tried to solve the problem with Rust macros and succeeded:

macro_rules! description {
    () => ( "my program" )
}
macro_rules! version {
    () => ( env!("CARGO_PKG_VERSION") )
}
macro_rules! version_string {
    () => ( concat!(description!(), " v", version!()) )
}

使用宏代替常量感觉有点难看,但它按预期工作.

It feels a bit ugly to use macros instead of constants, but it works as expected.

这篇关于如何在 Rust 中连接静态字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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