-3

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"]
  1. ttf_context is moved. I can solve this one, but by changing code in a ugly way.
  2. Font has lifetime bound on context. Cannot fix this one.

This documentation contains the declaration of Sdl2TtfContext and Font, should you find it useful. DOC

osamu
  • 983
  • 1
  • 9
  • 13
  • 2
    Questions seeking debugging help ("**why isn't this code working?**") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it **in the question itself**. Questions without a **clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Tim Diekmann Apr 10 '18 at 08:02
  • Tim, I updated the code. Now it includes a shortest code example. – osamu Apr 10 '18 at 21:16
  • Can you please add the error output? – Tim Diekmann Apr 10 '18 at 22:22

1 Answers1

0

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);
}
osamu
  • 983
  • 1
  • 9
  • 13