viraptor
viraptor

Reputation: 34205

Way to create inline static values

Sometimes I'd like to use some complex values with static lifetime, but defining them explicitly is tedious. Is there a way to turn something like this:

const PATH: &'static [&'static str] = &["foo", "bar", "baz"];
...
    do_things(PATH);

into something closer to this?

do_things(&["foo", "bar", "baz"]);

The function takes a &'static [&'static str] argument.

Upvotes: 1

Views: 484

Answers (2)

DK.
DK.

Reputation: 59115

If you're doing this a lot, and for a specific type of array, you can write a macro to simplify things:

// "Constant Array of STR"
macro_rules! castr {
    ($($es:expr),* $(,)*) => {
        {
            const C: &'static [&'static str] = &[$($es),*];
            C
        }
    };
}

fn main() {
    test(castr!["a", "b", "penguin"]);
}

fn test(ss: &'static [&'static str]) {
    println!("{:?}", ss);
}

Upvotes: 3

Steve Klabnik
Steve Klabnik

Reputation: 15559

Currently, at this time, there is not. You have to write your initial code.

Upvotes: 2

Related Questions