Get a common attribute from ordinal without self-training?

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;
}

#[derive(Clone)]
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()
    }
}

//struct Data2(f64);
//impl Foo for Data2...
//impl TypedFoo<Data2> for Data2..

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>.

+4
1

, ,

fn convert<T>(x: &Box<Foo>) -> &TypedFoo<T>

, , Box TypedFoo<T> T. - . , .

, , , , .

- , TypedFoo, Foo. .

- trait Foo , (TypeId, *const ()). - , . .

Vec conversion_registrar. &'static [(TypeId, *const ())], lazy_static.

+3

Source: https://habr.com/ru/post/1678548/


All Articles