I have two traits, one serial number ( Foo), another common ( TypedFoo<T>). I have several structures, each of which has two features.
Is it possible to convert from Footo TypedFoo<T>without converting to an intermediate structure?
trait Foo {
fn f(&mut self);
}
trait TypedFoo<T> {
fn get(&self) -> T;
}
struct Data(i32);
impl Foo for Data {
fn f(&mut self) {
self.0 += 1;
}
}
impl TypedFoo<Data> for Data {
fn get(&self) -> Data {
self.clone()
}
}
fn main() {
let v: Vec<Box<Foo>> = vec![Box::new(Data(1))];
}
I can change Footo this:
trait Foo {
fn f(&mut self);
fn get_self(&self) -> &Any;
}
Then we get v[0].get_self() downcast_refto Data, and then Datato &TypedFoo<Data>.
But is it possible to obtain &TypedFoo<Data>from &Foowithout knowledge of the βdata typeβ some analogue Any, but for a sign.
I assume the syntax is as follows:
let foo: &Foo = ...;
if let Some(typed_foo) = foo.cast::<Data>() {
}
?
. , , :
trait Foo {
fn f(&mut self);
fn as_typed_foo(&self) -> &TypedFoo;
}
TypedFoo , . :
trait Foo {
fn f(&mut self);
fn cast(&mut self, type_id: ::std::any::TypeId) -> Option<*mut ::std::os::raw::c_void>;
}
, *mut TypedFoo<T> β *mut ::std::os::raw::c_void, *mut TypedFoo<T>.