title: Understanding and relationship between Box, ref, & and *
body: <p>I'm a bit confused about how pointers work in Rust. There's <code>ref</code>, <code>Box</code>, <code>&amp;</code>, <code>*</code>, and I'm not sure how they work together.</p>
  
  <p>Here's how I understand it currently:</p>
  
  <ol>
  <li><code>Box</code> isn't really a pointer - it's a way to allocate data on the heap, and pass around unsized types (traits especially) in function arguments.</li>
  <li><p><code>ref</code> is used in pattern matching to borrow something that you match on, instead of taking it. For example,</p>
  
  <pre><code>let thing: Option&lt;i32&gt; = Some(4);
  match thing {
      None =&gt; println!("none!"),
      Some(ref x) =&gt; println!("{}", x), // x is a borrowed thing
  }
  println!("{}", x + 1); // wouldn't work without the ref since the block would have taken ownership of the data
  </code></pre></li>
  <li><p><code>&amp;</code> is used to make a borrow (borrowed pointer). If I have a function <code>fn foo(&amp;self)</code> then I'm taking a reference to myself that will expire after the function terminates, leaving the caller's data alone. I can also pass data that I want to retain ownership of by doing <code>bar(&amp;mydata)</code>.</p></li>
  <li><code>*</code> is used to make a raw pointer: for example, <code>let y: i32 = 4; let x = &amp;y as *const i32</code>. I understand pointers in C/C++ but I'm not sure how this works with Rust's type system, and how they can be safely used. I'm also not sure what the use cases are for this type of pointer. Additionally, the <code>*</code> symbol can be used to dereference things (what things, and why?).</li>
  </ol>
  
  <p>Could someone explain the 4th type of pointer to me, and verify that my understanding of the other types is correct? I'd also appreciate anyone pointing out any common use cases that I haven't mentioned.</p>