Rust函数没有静态寿命吗? [英] Rust function does not have static lifetime?

查看:106
本文介绍了Rust函数没有静态寿命吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编译以下简单代码:

I am trying to make this simple code compile:

fn dox(x: u8) -> u8 { x*2 }

fn main() {
    let cb: &'static (Fn(u8) -> u8) = &dox;
}

但是在Rust 1.9中失败:

But it fails with Rust 1.9:

x.rs:4:40: 4:43 error: borrowed value does not live long enough
x.rs:4     let cb: &'static (Fn(u8) -> u8) = &dox;
                                              ^~~
note: reference must be valid for the static lifetime...
x.rs:4:44: 5:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 4:43
x.rs:4     let cb: &'static (Fn(u8) -> u8) = &dox;
x.rs:5 }
error: aborting due to previous error

自由函数没有静态寿命的可能性如何?这段代码怎么会不安全?

How is it possible that a free function does not have static lifetime? How could this code be unsafe?

推荐答案

从Rust 1.21开始,将自动执行静态升级",并且原始代码将按原样编译.

As of Rust 1.21, "static promotion" is performed automatically and your original code compiles as-is.

此代码也可以编译:

fn main() {
    let a: &'static i32 = &5;
}

此外,可以将不会从其环境中捕获任何内容的闭包自动转换为函数指针,因此您也无需创建单独的函数:

Additionally, closures which do not capture anything from their environment can be automatically converted to function pointers, so you don't need to create a separate function, either:

fn main() {
    let cb: fn(u8) -> u8 = |x| x * 2;
}

这篇关于Rust函数没有静态寿命吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆