4

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.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
RedCrafter LP
  • 174
  • 1
  • 8

1 Answers1

0

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);
}
  • That's a great solution. Didn't know that you could use concat! in a const context. The only thing missing is, that the macro parameters are not i32. But that's easily fixable by adding 2 constants of i32 in the macro and assign the parameters to it. – RedCrafter LP May 21 '22 at 09:28