由于需求冲突,无法推断自动引用的适当生命周期

我的代码中存在特定功能的生命周期问题。我正在按照一个教程尝试学习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的了解还不足以解决此问题,或者那是否正确。


白板的微信
浏览 455回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP