我的代碼中存在特定功能的生命周期問題。我正在按照一個(gè)教程嘗試學(xué)習(xí)Rust和SDL。該教程稍早一些,自編寫以來,SDL庫已經(jīng)發(fā)生了變化,因此,我在跟進(jìn)的同時(shí)也將其調(diào)整為適用于最新版本的Rust-SDL。生存期問題在此函數(shù)中: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>該實(shí)現(xiàn)的struct對(duì)象如下所示: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在函數(shù)參數(shù)中添加一個(gè)生存期,當(dāng)我這樣做時(shí),這會(huì)導(dǎo)致級(jí)聯(lián)效果,從而將生存期添加到調(diào)用原始方法的所有方法中,一直到main()無濟(jì)于事。由于我仍然不熟悉Rust,因此我不確定生命周期沖突存在于何處或?yàn)槭裁磿?huì)這樣。作為一個(gè)猜測(cè),我Font認(rèn)為正在生成的對(duì)象應(yīng)該在該方法的結(jié)尾處消失,而是將其裝入生命周期為'window并且這兩個(gè)沖突的哈希圖中。不過,我對(duì)Rust的了解還不足以解決此問題,或者那是否正確。
- 1 回答
- 0 關(guān)注
- 558 瀏覽
添加回答
舉報(bào)
0/150
提交
取消