The trick to do this in safe code is Option::take()
, which lets you transform &mut Option<T>
into T
:
if TypeId::of::<T>() == TypeId::of::<U>() {
// Transmute from U to T.
let t1 = t;
let mut u_opt = Some(u);
let t2 = (&mut u_opt as &mut dyn std::any::Any)
.downcast_mut::<Option<T>>()
.unwrap()
.take()
.unwrap();
same(t1, t2)
}