我的代碼中存在特定功能的生命周期問題。我正在按照一個教程嘗試學習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加載字體ttf_context并將其加載到哈希圖中。Rust編譯器建議我self在函數參數中添加一個生存期,當我這樣做時,這會導致級聯效果,從而將生存期添加到調用原始方法的所有方法中,一直到main()無濟于事。由于我仍然不熟悉Rust,因此我不確定生命周期沖突存在于何處或為什么會這樣。作為一個猜測,我Font認為正在生成的對象應該在該方法的結尾處消失,而是將其裝入生命周期為'window并且這兩個沖突的哈希圖中。不過,我對Rust的了解還不足以解決此問題,或者那是否正確。
- 1 回答
- 0 關注
- 554 瀏覽
添加回答
舉報
0/150
提交
取消