ruststring-interpolationcompile-time-constant

Interpolate string in const function


Im trying to make a function similar to this

pub const fn insert(num1:i32, num2:i32) -> &'static str { 
    formatcp!("n1:{}, n2:{}" , num1, num2) 
} 

But num1/num2 are not const. I think this would be possible as a macro but im not experienced in macros.


Solution

  • Does it help?

    macro_rules! insert {
        ($n1:expr, $n2:expr) => {
            concat!("n1: ", $n1, " , n2: ", $n2)
        };
    }
    
    const TEST_1: &str = insert!(1, 2);
    const TEST_2: &str = insert!(2, 3);
    
    fn main() {
        println!("{}", TEST_1);
        println!("{}", TEST_2);
    }