编译器无缘无故地将'static推断为生命周期

问题描述 投票:0回答:1

我正像在官方示例Rusttype中一样,将here的gpu_cache功能与Glium一起使用,但是我遇到了一些意想不到的生命周期问题。也就是说,在此代码中:

// ...

let font = rusttype::Font::try_from_bytes(include_bytes!("../fonts/alegreya/Alegreya-Regular.otf")).expect("Couldn't load font");
let font_ref = std::rc::Rc::new(&font); // line 36 is here

let (cache_width, cache_height) = cache_dims(&display);
let mut cache = rusttype::gpu_cache::Cache::builder()
    .dimensions(cache_width, cache_height)
    .build();

event_loop.run(move |event, _, control_flow| {
    match event {
        Event::RedrawRequested(_) => {
            let mut target = display.draw();
            render::exec(&mut target, &mut ctx, font_ref.clone(), &mut cache);
            target.finish().unwrap();
        }

        // ...

        _ => ()
    }
});
// line 66 is here, at the end of main()

font_ref分配,特别是&font参考上触发错误:

`font` does not live long enough
borrowed value does not live long enough
rustc(E0597)
main.rs(66, 1): `font` dropped here while still borrowed
main.rs(36, 17): argument requires that `font` is borrowed for `'static`

据我所知,编译器推断&font必须具有'static生存期,因为包含它的Rc作为参数传递给我的render::exec函数,该函数具有以下签名:

pub fn exec<'font>(target: &mut glium::Frame, ctx: &mut Context, font: std::rc::Rc<&'font rusttype::Font>, cache: &mut gpu_cache::Cache<'font>)

因此,它必须表示最初是cache被推断为具有'static生存期,我不知道为什么会这样。我只在cache函数中使用了render::exec

for glyph in glyphs {
    cache.queue_glyph(0, glyph.clone());
}

rusttype::gpu_cache::Cache::queue_glyph的签名如下:

pub fn queue_glyph(&mut self, font_id: usize, glyph: PositionedGlyph<'font>)

其中'font实际上是赋予Cache类型的生存期参数。我要传递给glyphsqueue_glyph是通过rusttype::Font::layout方法检索的,如下所示:

let glyphs: Vec<_> = font.layout(buffer_str.as_ref(), scale, offset).collect();

这意味着根据the method's signatureLayoutIterlayout的返回类型)的Iterator implementation,这些字形的寿命与字体相同。因此,这里发生了一种循环推理:应为缓存提供具有Font生存期的字形,并且出于生存期匹配的原因,Font及其引用layout的引用都应具有Cache的生存期。 >

但是,即使有所有这些[[我都找不到编译器在此处要求提供'static引用的明确原因,也没有一种绕开它的方法。

因此,欢迎您提供任何帮助。] >我正尝试在此处的官方示例中将Rusttype的gpu_cache功能与Glium一起使用,但是我遇到了一些意想不到的生命周期问题。也就是说,在此代码中:// ... let font = ...
rust lifetime
1个回答
0
投票
正如上面@CoronA所评论的,您几乎永远不会将Rc与引用一起使用,因为成为Rc的原因是使对象的生存时间尽可能长,而忽略了生命周期。如果包装参考,您将一无所获。

尝试类似的事情,显然未经测试:

© www.soinside.com 2019 - 2024. All rights reserved.