[英]Why doesn't this instance of a TextureCreator<WindowContext> live long enough?
我正在使用 crates.io 中的 sdl2 crate 在 Rust 中编写一个图形程序。
我在main.rs
中创建了这个结构:
struct GameObject {
name: &'static str,
pub texture: Option<Texture<'static>>
}
impl GameObject {
pub fn new(name: &'static str) -> Self {
Self { name, texture: None }
}
pub fn set_texture(&mut self, t: Option<Texture<'static>>) {
self.texture = t;
}
}
我正在尝试使用以下代码行向GameObject
的实例添加纹理(其中canvas
是我主窗口中window.into_canvas().build().unwrap()
的结果):
let tc = canvas.texture_creator();
let mut g = GameObject::new("obj");
g.texture = Some(tc.load_texture("image.png").unwrap());
导致此错误:
error[E0597]: `tc` does not live long enough
--> src/main.rs:30:22
|
30 | g.texture = Some(tc.load_texture("image.png").unwrap());
| ^^---------------------------
| |
| borrowed value does not live long enough
| argument requires that `tc` is borrowed for `'static`
这在我的程序中意味着什么?
欢迎来到堆栈溢出社区。
要理解错误,您需要知道什么是'static
生命周期”。
'static
生命周期是可能的最长生命周期,并且持续到正在运行的程序的生命周期。
'static
生命周期也可能被强制缩短为更短的生命周期。
所以你的例子有评论:
// create a `tc` vriable with local lifetime 'a
let tc = canvas.texture_creator();
// "obj" has a static lifetime , and g has a local lifetime 'b
let mut g = GameObject::new("obj");
// here you try to put a variable with lifetime 'c (returned by load_texture
// that is probably equal to 'a) into a variable `g.texture` that is declared
// to contain `'static` lifetime
// lifetime of "image.png" is `'static` on input of `load_texture()` function
// but could be shorter in implementation.
g.texture = Some(tc.load_texture("image.png").unwrap());
为了让它工作,你可以尝试使用lazy-static来声明 Texture with 'static
lifetime.
如果您看到编译器错误 - 您可以随时通过 cmd 要求 cargo 向您解释:
cargo --explain E0597
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.