Static string extension

Hi guys,

i'm trying to write a method or a closure, which extends an arbitrary, but constant, string by another constant string. For example:

fn extend_str_by_funword(aword: &str) -> &str {
    aword + "_funword"
}

The method could be executed at compile time, because it would be called only with static strings, which are known at compile time.

Can anyone understand, what I'm trying to do? Is it possible to do it by a const fn or by a kind of global closure?

Thanks and kind regards,
Michael

Thank's! But it works only with literals given directly, I'm not allowed to use it within a function with a passed &str

For a string to be known at compile time it must be a string literal. &str is just a view onto any string slice, even one at runtime:

fn read_str (s: &'_ str) {
   // ...
}

fn main ()
{
    let s: String = ::std::env::args().next().unwrap();
    read_str(&s); // no error here
}

And even a &'static str may not have existed at compile time: 'static is a forward-guarantee, it has nothing to do with the past:

fn read_static_str (s: &'static str)
{
    // ...
}

fn main ()
{
    let s: String = ::std::env::args().next().unwrap();
    let s: &'static str = &*Box::leak(s.into_boxed_str());
    read_static_str(s);
}
3 Likes

Is it possible to specify string literal as a parameter?

And, is it possible to turn something like
pub const MAGIC_COMMAND: &str = "CMD01";
into a string literal at compile time?

I tried to solve this problem by writing a macro on my own, but still having some problems to get a string extension at compile time - when I'm using const like shown above... This is for a kind of IC-driver-library. The IC understands a couple of ASCII-commands and I want to provide a central module with available commands and methods to use them easier... rather than to force every user to write those ASCII-commands over and over again.

Thanks,
Michael

You could write this as a "function"-like macro:

macro_rules! extend_str_by_funword {
    ($s:literal) => ( concat!($s, "_funword") )
}

fn main() {
    println!(extend_str_by_funword!("foo"));
}

const-concat does this with some very interesting compile-time evaluation techniques (or “dark, evil magicks,” according to the README file).

2 Likes

Yeah, that is working - thank's a lot!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.