How to concatenate static strings in Rust

前端 未结 2 978
深忆病人
深忆病人 2020-12-20 11:34

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:



        
相关标签:
2条回答
  • 2020-12-20 11:56

    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.

    0 讨论(0)
  • 2020-12-20 12:03

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

    0 讨论(0)
提交回复
热议问题