title: Is it safe and defined behavior to transmute between a T and an UnsafeCell<T>?
body: <p>A <a href="https://stackoverflow.com/q/50425910/155423">recent question</a> was looking for the ability to construct self-referential structures. In discussing possible answers for the question, one potential answer involved using an <a href="https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html" rel="noreferrer"><code>UnsafeCell</code></a> for interior mutability and then "discarding" the mutability through a <a href="https://doc.rust-lang.org/std/mem/fn.transmute.html" rel="noreferrer"><code>transmute</code></a>.</p>
  
  <p>Here's a small example of such an idea in action. I'm not deeply interested in the example itself, but it's just enough complication to require a bigger hammer like <code>transmute</code> as opposed to just using <a href="https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#new" rel="noreferrer"><code>UnsafeCell::new</code></a> and/or <a href="https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.into_inner" rel="noreferrer"><code>UnsafeCell::into_inner</code></a>:</p>
  
  <pre><code>use std::{
      cell::UnsafeCell, mem, rc::{Rc, Weak},
  };
  
  // This is our real type.
  struct ReallyImmutable {
      value: i32,
      myself: Weak&lt;ReallyImmutable&gt;,
  }
  
  fn initialize() -&gt; Rc&lt;ReallyImmutable&gt; {
      // This mirrors ReallyImmutable but we use `UnsafeCell` 
      // to perform some initial interior mutation.
      struct NotReallyImmutable {
          value: i32,
          myself: Weak&lt;UnsafeCell&lt;NotReallyImmutable&gt;&gt;,
      }
  
      let initial = NotReallyImmutable {
          value: 42,
          myself: Weak::new(),
      };
  
      // Without interior mutability, we couldn't update the `myself` field
      // after we've created the `Rc`.
      let second = Rc::new(UnsafeCell::new(initial));
  
      // Tie the recursive knot 
      let new_myself = Rc::downgrade(&amp;second);
  
      unsafe {
          // Should be safe as there can be no other accesses to this field
          (&amp;mut *second.get()).myself = new_myself;
  
          // No one outside of this function needs the interior mutability
          // TODO: Is this call safe?
          mem::transmute(second)
      }
  }
  
  fn main() {
      let v = initialize();
      println!("{} -&gt; {:?}", v.value, v.myself.upgrade().map(|v| v.value))
  }
  </code></pre>
  
  <p>This code appears to print out what I'd expect, but that doesn't mean that it's safe or using defined semantics.</p>
  
  <p>Is transmuting from a <code>UnsafeCell&lt;T&gt;</code> to a <code>T</code> memory safe? Does it invoke undefined behavior? What about transmuting in the opposite direction, from a <code>T</code> to an <code>UnsafeCell&lt;T&gt;</code>?</p>