如何解决 SDL2 的这个锈蚀生命周期问题? [英] How to solve this rust lifetime bound issue of SDL2?
本文介绍了如何解决 SDL2 的这个锈蚀生命周期问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 sdl2 ttf 渲染一些字体.sdl2 中 Font 类型的类型对使用 PhantomData 的上下文具有生命周期依赖性.我觉得很难使用.这是我尝试使用的最少代码.
I'm trying to render some font using sdl2 ttf. The type of Font type in sdl2 has a lifetime dependency on the context using PhantomData. I find it very difficult to use. Here's the the minimal code I'm trying to use.
main.rs
extern crate sdl2;
use sdl2::ttf::{self, Font};
use sdl2::ttf::Sdl2TtfContext;
struct App<'ttf> {
ctx: Sdl2TtfContext,
glyph_renderer: GlyphRenderer<'ttf>,
}
impl<'ttf> App<'ttf> {
fn render(&self) {}
}
struct GlyphRenderer<'ttf> {
font: Font<'ttf, 'static>,
}
fn main() {
let ttf_context = ttf::init().unwrap();
let font = ttf_context.load_font("./assets/Supermercado-Regular.ttf", 50).unwrap();
let glyph_renderer = GlyphRenderer { font };
let app = App {
ctx: ttf_context,
glyph_renderer,
};
app.render();
}
Cargo.toml
[package]
name = "demo-rust"
version = "0.1.0"
authors = ["clojure"]
[dependencies.sdl2]
version = "0.31.0"
default-features = false
features = ["ttf"]
- ttf_context 已移动.我可以解决这个问题,但要以一种丑陋的方式更改代码.
- 字体在上下文中具有生命周期限制.无法修复此问题.
本文档包含 Sdl2TtfContext
和 Font
的声明,如果您觉得有用的话.文档
This documentation contains the declaration of Sdl2TtfContext
and Font
, should you find it useful. DOC
推荐答案
好的,我可以通过将上下文创建移到外部作用域来解决这个问题.它不能放在结构上.
Alright, I am able to fix this issue by moving context creation to the outer scope. It cannot be put on a struct.
fn start(ttf_context: &Sdl2TtfContext) {
let font = ttf_context.load_font("./assets/Supermercado-Regular.ttf", 50).unwrap();
let glyph_renderer = GlyphRenderer { font };
let app = App {
glyph_renderer,
};
app.render();
}
fn main() {
let ttf_context = ttf::init().unwrap();
start(&ttf_context);
}
这篇关于如何解决 SDL2 的这个锈蚀生命周期问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文