rustpyo3

How to bypass object safety in Rust


I'm not particularly familiar with how Rust unsafe is used, but, essentially, I need to be able to create a dynamic trait object (whose methods will never be called while it is in the form of a trait object because it gets downcasted), but the trait which I need to make the object out of has Sized as a super-trait, which means that, for object safety, I can't create a dynamic type.

I can't create my own trait because the trait is defined and being used by a crate that I am not the author of, so I was wondering if there is some way of bypassing the object safety requirements of trait objects.

Alternatively, if there is some equivalent to pyo3's IntoPy<Py<PyTuple>> that doesn't have Sized as a supertrait, but can be used as arguments to call a python function in pyo3, that would also work.


Solution

  • If you want to make a trait object out of a value but you are only going to downcast it, it sounds a lot like you want to use Any as Box<dyn Any>. This trait has a downcast method you can use to attempt to cast the value to a concrete type.