0

I have a simple template like "hello {blank} how are you?"

and 2 separate functions that need to hard code "blank" with static values (can be known at compile time).

I don't want to hard code this templated text to the functions. I'm looking for something like a C #DEFINE macro which will just "stick" the value into the string.

Contrived:

// my macro/ const function or what ever needs to be here:
const fn / macro! fill_text(name: &str) -> {return format!("hello {name} how are you") } // at compile time should be evaluated, not at run time

fn say_hello_to_john() ->&'static str { 
  fill_text("john")
}

fn say_hello_to_jane() -> &'static str {
  fill_text("jane")
}

Tried this but it doesn't yield a static string:

macro_rules! fill_text {
   $text:expr => {
      format!("hello {} how are you", $text) // how to make this static?
   }
}
Avba
  • 14,822
  • 20
  • 92
  • 192
  • I would say use the lazy_static crate, but you'll have the allocation and runtime format overhead when initialized. Perhaps a build script? – MeetTitan Jun 02 '22 at 17:14
  • isn't there a way to just "replace" strings in a macro. In c it would be something as along the lines of adding the # symbol like `#define template(name) How are you #name`. doesn't rust have this concept? – Avba Jun 02 '22 at 17:18
  • Also are you just `Display`ing the `&'static str`s? If so, you could make a wrapper to `impl Display` around `[&'static str; 3]` that writes the strings one by one on the same line. – MeetTitan Jun 02 '22 at 17:20
  • You can replace the individual bytes in a `&'static mut str` but you have to be careful to align to utf8 character borders and you can't change the size (changing the size requires an allocation and can't be const) – MeetTitan Jun 02 '22 at 17:21
  • Look into the approach I mentioned in my second comment, the [arraystring crate](https://docs.rs/arraystring/latest/arraystring/), the [unicode_segmentation crate](https://docs.rs/unicode-segmentation/latest/unicode_segmentation/), and the [bstr crate](https://docs.rs/bstr/latest/bstr/) – MeetTitan Jun 02 '22 at 17:25

0 Answers0