【问题标题】:Way to create inline static values创建内联静态值的方法
【发布时间】:2016-08-10 23:22:23
【问题描述】:

有时我想使用一些具有静态生命周期的复杂值,但明确地定义它们是乏味的。有没有办法变成这样:

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

更接近这个?

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

该函数采用&'static [&'static str] 参数。

【问题讨论】:

  • 如果我可能会问:为什么函数的参数需要是'static?为什么不是正常的通用生命周期?
  • 因为它是stackoverflow.com/questions/38884989/… 解决方案的一部分但是这个问题本身对我来说很有趣。

标签: rust


【解决方案1】:

如果你经常这样做,并且对于特定类型的数组,你可以编写一个宏来简化事情:

// "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);
}

【讨论】:

  • 我喜欢这个!谢谢。
【解决方案2】:

目前,在这个时候,没有。您必须编写初始代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2015-10-07
    • 2021-07-03
    • 1970-01-01
    • 2011-02-27
    相关资源
    最近更新 更多