gpt4 book ai didi

rust - 创建具有静态生存期的匿名变量时,最佳实践是什么?

转载 作者:行者123 更新时间:2023-12-03 11:35:41 24 4
gpt4 key购买 nike

这个问题分为两部分:(1)传递高阶函数静态引用以使它们(参数)具有足够长的生存期是一种好习惯吗? (2)创建具有静态生存期的匿名变量的最佳方法是什么?

这里是上下文:我有一个元函数,该函数根据其参数返回一个闭包。为了确保参数生命周期足够长,它们必须是静态引用。例如。,

pub enum Uncloneable { Variant }

pub fn get_getter(param:&'static Uncloneable)
-> Box<dyn Fn() -> &'static Uncloneable> {
Box::new(move || { param })
}

但是我不想每次调用 const时都用很多 get_getter定义来弄乱我的代码,例如
fn main() {
let _result = get_getter({
const VAR:Uncloneable = Uncloneable::Variant;
&VAR
});
}

我当前的解决方案是使用宏:
#[macro_export]
macro_rules! staticify {
($type:tt :: $variant:tt) => {{
const VAR:$type = $type::$variant;
&VAR
}};
}

fn main() {
let _result = get_getter(staticify!(Uncloneable::Variant));
}

效果很好,但我担心我可能会在这里重新发明轮子(甚至犯下一些反模式)。

Here's he full code on Rust Playground.

最佳答案

我认为您的宏不是反模式,但在这种情况下不一定很有用。 const不会为该值分配任何存储空间,它只是在编译时进行替换,因此您的代码与以下代码相同:

fn main() {
let _result = get_getter(&Uncloneable::Variant);
}

换句话说,使用 const来存储值既没有必要,也没有不同。

另外,引用会自动提升为 &'static UncloneableRust reference explains:

When using a value expression in most place expression contexts, a temporary unnamed memory location is created initialized to that value and the expression evaluates to that location instead, except if promoted to 'static. Promotion of a value expression to a 'static slot occurs when the expression could be written in a constant, borrowed, and dereferencing that borrow where the expression was originally written, without changing the runtime behavior. That is, the promoted expression can be evaluated at compile-time and the resulting value does not contain interior mutability or destructors (these properties are determined based on the value where possible, e.g. &None always has the type &'static Option<_>, as it contains nothing disallowed).



因此,从本质上讲,如果您可以像代码一样使用常量,则也可以直接引用该值,如果可以的话,它将自动提升为 'static引用。

关于rust - 创建具有静态生存期的匿名变量时,最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61124798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com