Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate static strings in Rust

Tags:

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?

like image 862
CodeMonkey Avatar asked Feb 02 '16 15:02

CodeMonkey


People also ask

What is a static string in Rust?

5 months ago. by John Otieno. A static variable refers to a type of variable that has a fixed memory location. They are similar to constant variables except they represent a memory location in the program.

Why does rust have two string types?

Rust doesn't sugar coat a lot of the ugliness and complexity of string handling from developers like other languages do and therefore helps in avoiding critical mistakes in the future. By construction, both string types are valid UTF-8. This ensures there are no misbehaving strings in a program.


2 Answers

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.

like image 174
CodeMonkey Avatar answered Sep 20 '22 10:09

CodeMonkey


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!.

like image 33
oli_obk Avatar answered Sep 23 '22 10:09

oli_obk