为什么“静态函数参数"不能为整个程序生成一些内容? [英] Why doesn't a 'static function argument make something live for the entire program?

查看:37
本文介绍了为什么“静态函数参数"不能为整个程序生成一些内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是不明白 'static 的行为.在以下代码中,say_foo 有效但 say_bar 无效:

I still don't understand the behavior of 'static. In the following code, say_foo works but say_bar does not:

fn say_foo(_: &String) -> &str {
    "foo!"
}
fn say_bar(_: &'static String) -> &str {
    "bar!"
}

fn main() {
    let f = "f".to_string();
    let f2 = say_foo(&f); // ok:)
    println!("{}", f2);

    let b = "b".to_string();
    let b2 = say_bar(&b); // error:`b` does not live long enough
    println!("{}", b2);
}

即使我将 reference 传递给两个函数,传递变量的预期寿命在 say_foosay_bar 之间是不同的.

Even if I pass reference to both functions, the life expectancy of the passed variable is different between say_foo and say_bar.

关于生命周期的章节中,我发现'static 是一个信号,它使某些东西的生命周期存在于整个程序中.

In the chapter about lifetimes, I found that 'static is a signal that makes a lifetime of something to live in the entire program.

但是这个 'static 似乎不是那样的:bb2(和 f>).

But this 'static does not seem to act like that: b was released before b2 (and f).

'static 是什么意思?

推荐答案

您犯了一个非常常见的错误,试图规定引用的生命周期,但是生命周期是描述性的,而不是规定性的.

You are making a very common mistake, attempting to dictate the lifetime of a reference, however lifetimes are descriptive, not prescriptive.

'static 是在程序的整个持续时间内存在的所有事物的生命周期,例如:

'static is the lifetime of all things that live for the entire duration of the program, for example in:

const ID: usize = 4;

fn print(i: &'static usize) { println!("{}", i); }

fn main() {
    print(&ID);
}

ID 的生命周期是 'static,因此我可以将 &ID 传递给需要 &' 的函数静态使用.

The lifetime of ID is 'static and therefore I can pass &ID to a function expecting a &'static usize.

如果我在 main 中有一个 usize 类型的变量:

If I have a variable of type usize in main:

fn main() {
    let i = 4usize;
    print(&i);
}

然而,编译器会抱怨 i 的寿命不够长,因为 &'static usize 作为参数类型是一个要求:它说只有至少与 'static (这是可能的最长生命周期)一样长的变量才会被接受.而且i的生​​命周期较短,所以被拒绝了.

the compiler will however complain that i does not live long enough because &'static usize as a parameter type is a requirement: it says that ONLY variables which live at least as long as 'static (which is the longest possible lifetime) will be accepted. And i's lifetime is shorter, so it's rejected.

重申:Rust 中的所有事物都有一个内在的生命周期,'a 符号只是一种观察它的方式,而不是>修改它.

To reiterate: all things in Rust have an intrinsic lifetime, and the 'a notation is only a way of observing it not a way of modifying it.

这篇关于为什么“静态函数参数"不能为整个程序生成一些内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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