【发布时间】:2017-05-07 07:21:13
【问题描述】:
我的代码中的特定函数存在生命周期问题。我正在学习一个教程,试图学习 Rust 和 SDL。该教程稍旧,并且 SDL 库在编写后发生了变化,因此我在跟进的同时也将其调整为最新版本的 Rust-SDL。
生命周期问题在这个函数中:
pub fn ttf_str_sprite(&mut self, text: &str, font_path: &'static str, size: i32, color: Color) -> Option<Sprite> {
if let Some(font) = self.cached_fonts.get(&(font_path, size)) {
return font.render(text).blended(color).ok()
.and_then(|surface| self.renderer.create_texture_from_surface(&surface).ok())
.map(Sprite::new)
}
//::sdl2_ttf::Font::from_file(Path::new(font_path), size).ok()
self.ttf_context.load_font(Path::new(font_path), size as u16).ok()
.and_then(|font| {
self.cached_fonts.insert((font_path, size), font);
self.ttf_str_sprite(text, font_path, size, color)
})
}
尤其是self.ttf_context.load_font(Path::new(font_path), size as u16).ok() 行。上面的注释行是旧SDL版本的字体加载方法。
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src\phi/mod.rs:57:26
|
57 | self.ttf_context.load_font(Path::new(font_path), size as u16).ok()
| ^^^^^^^^^
|
help: consider using an explicit lifetime parameter as shown: fn ttf_str_sprite(&'window mut self, text: &str, font_path: &'static str,
size: i32, color: Color) -> Option<Sprite>
该实现的结构对象如下所示:
pub struct Phi<'window> {
pub events: Events,
pub renderer: Renderer<'window>,
pub ttf_context: Sdl2TtfContext,
cached_fonts: HashMap<(&'static str, i32), ::sdl2_ttf::Font<'window>>
}
该方法正在尝试从 Phi 的 ttf_context 加载字体并将其加载到哈希图中。 Rust 编译器建议我在函数参数中为 self 添加生命周期,当我这样做时,会导致级联效应为每个调用原始方法的方法添加生命周期,一直到 main() 并且没有帮不上什么忙。
由于我还是 Rust 的新手,我不确定生命周期冲突在哪里或为什么会发生这种情况。作为一种猜测,我认为正在生成的 Font 对象应该随着该方法的结束而死,而是被加载到一个生命周期为 'window 的哈希图中,这两个冲突。不过,我对 Rust 的了解还不足以解决这个问题,或者这是否正确。
【问题讨论】: