CodeMonkey
CodeMonkey

Reputation: 744

How to concatenate static strings in 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);

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

Upvotes: 33

Views: 14511

Answers (3)

sshine
sshine

Reputation: 16105

You can concatenate named and literal constants of various types with the const_format crate.

This crate was available since August 2020, so this answer has only been possible to make in retrospect:

use const_format::concatcp;

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

This macro even lets you concatenate number constants / literals into one &'static str.

Upvotes: 1

CodeMonkey
CodeMonkey

Reputation: 744

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.

Upvotes: 24

oli_obk
oli_obk

Reputation: 31163

The compiler error is

error: expected a literal

A literal is anything you type directly like "hello" or 5. The moment you start working with constants, you are not using literals anymore, but identifiers. So right now the best you can do is

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

Since the env! macro expands to a literal, you can use it inside concat!.

Upvotes: 21

Related Questions