我的代码中的某个特定函数存在生命周期问题.我正在学习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>
该实现的struct对象如下所示:
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's ttf_context
中加载字体,并将其加载到hashmap中.Rust编译器建议我在函数参数中为self
添加一个生存期,当我这样做时,会对每个调用原始方法的方法添加生存期产生级联效应,一直到main()
,没有任何帮助.
由于我还是一个Rust 的新手,我不确定这一生的冲突在哪里,也不知道为什么会发生.作为猜测,我认为正在生成的Font
个对象应该随着该方法的结束而消亡,但相反,它被加载到一个生存期为'window
的hashmap中,这两个冲突.不过,我对Rust 的了解还不足以修复它,或者说这是否正确.