If I have two types with the same TypeId
, is it able to safely convert one type to the other? If so, is the following code a correct way of conversion?
pub fn new<T>(message: T) -> Self {
let type_id = message.type_id();
if type_id == TypeId::of::<Self>() {
let ptr: Box<dyn Any> = Box::new(message);
return *ptr.downcast().unwrap()
}
// ...
Roundtripping through dyn Any
would be a safe way to do the type conversion.
That code won't work without trait bounds, and you haven't included the definition of type_id
, so
.
yes, if they have the same TypeId
, they are the same type.
it is correct, but it's unclear to me what you are trying to do with this. generic types are monomophized at compile time. if you are trying to emulate "specialization", then it could make some sense. if you are trying to do runtime reflection, then this code probably doesn't do what you expected.
nevertheless, it is correct, but you can do it more efficiently (but requires unsafe
):
if type_id == TypeId::of::<Self>() {
let ptr = &raw const message;
// safety: cast is a no-op between same type
// old value called `forget()` after being `ptr::read()`
let value = unsafe { std::ptr::read(ptr.cast()) };
std::mem::forget(message);
return value
}