title: How do I convert between numeric types safely and idiomatically?
body: <blockquote>
  <p>Editor's note: This question is from a version of Rust prior to 1.0 and references some items that are not present in Rust 1.0. The answers still contain valuable information.</p>
  </blockquote>
  <p>What's the idiomatic way to convert from (say) a <code>usize</code> to a <code>u32</code>?</p>
  <p>For example, casting using <code>4294967295us as u32</code> works and the <a href="https://doc.rust-lang.org/0.12.0/reference.html#type-cast-expressions" rel="noreferrer">Rust 0.12 reference docs on type casting</a> say</p>
  <blockquote>
  <p>A numeric value can be cast to any numeric type. A raw pointer value can be cast to or from any integral type or raw pointer type. Any other cast is unsupported and will fail to compile.</p>
  </blockquote>
  <p>but <code>4294967296us as u32</code> will silently overflow and give a result of 0.</p>
  <p>I found <a href="https://doc.rust-lang.org/0.12.0/std/num/trait.ToPrimitive.html" rel="noreferrer"><code>ToPrimitive</code></a> and <a href="https://doc.rust-lang.org/0.12.0/std/num/trait.FromPrimitive.html" rel="noreferrer"><code>FromPrimitive</code></a> which provide nice functions like <code>to_u32() -&gt; Option&lt;u32&gt;</code>, but they're marked as unstable:</p>
  <blockquote>
  <p><code>#[unstable(feature = &quot;core&quot;, reason = &quot;trait is likely to be removed&quot;)]</code></p>
  </blockquote>
  <p>What's the idiomatic (and safe) way to convert between numeric (and pointer) types?</p>
  <p>The platform-dependent size of <code>isize</code> / <code>usize</code> is one reason why I'm asking this question - the original scenario was I wanted to convert from <code>u32</code> to <code>usize</code> so I could represent a tree in a <code>Vec&lt;u32&gt;</code> (e.g. <code>let t = Vec![0u32, 0u32, 1u32]</code>, then to get the grand-parent of node 2 would be <code>t[t[2us] as usize]</code>), and I wondered how it would fail if <code>usize</code> was less than 32 bits.</p>