繁体   English   中英

为什么这个 TextureCreator 实例没有<windowcontext>活够长吗?</windowcontext>

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM