title: Rust Pattern to Hold Reference to Builder in Struct
body: <p>I'm fairly new to Rust, and I am trying to use a library which wraps the SDL2 C library. Apologies for the abstract question, but I'm hoping this is a very common pattern with a solution that the Rust community can point me towards. I would like to be able to do something like this:</p>
  <pre><code>pub struct Gfx {
      texture_creator: TextureCreator&lt;WindowContext&gt;,
  }
  
  pub struct Sprite&lt;'a&gt; {
      texture: Texture&lt;'a&gt;,
  }
  
  impl Gfx {
      pub fn new() -&gt; Self {
          // do things to initialize a texture_creator
          Self {
              texture_creator
          }
      }
      pub fn build_sprite(&amp;self) -&gt; Sprite {
          let some_filepath = Path::new(&quot;/foo/bar/baz&quot;);
          let tmp = Surface::from_file(some_filepath).unwrap();
          let texture = self.texture_creator.create_texture_from_surface(tmp).unwrap();
  
          Sprite {
              texture: texture
          }
      }
  }
  </code></pre>
  <p>The problem is that when I want to use this in my code, the compiler will see something like:</p>
  <pre><code>let gfx = Gfx::new();
  let my_sprite = gfx.build_sprite();
  
  gfx.render() // or whatever else I want to do with gfx, which may be mutable... 
  </code></pre>
  <p>And the compiler will complain that I've borrowed mutably after borrowing immutably.</p>
  <p>I understand the problem the compiler is trying to prevent, namely since a reference to <code>TextureCreator</code> is held by <code>my_sprite</code>, it cannot guarantee that the reference to <code>TextureCreator</code> will not change after I begin using <code>my_sprite</code>. However, I don't really understand how to think about the problem from a Rust perspective to avoid this issue.</p>
  <p>How can I have a structure which holds a reference to something which creates children referencing itself? Is there a way I can tell the compiler, &quot;I promise that all my sprites will live at least as long as the <code>texture_creator</code> and that I promise when I borrow this structure to <code>build_sprite</code>, I will never alter anything?&quot;</p>