1
trait T {}
struct S;
impl T for S {}

fn use_trait_obj(o: Box<T>) -> Box<T> {
    // does some stuff ...
    o
}

fn main(){
    let s = S;
    let t: Box<T> = use_trait_obj(Box::new(s));
    let s: Box<S> = ...; // ?
}

Can I revert a trait object to its concrete type?

In my use-case, T is a fixed trait, S is a special implementation for testing purposes, and after calling the function I wish to check the internal fields of the object as part of the test.

I tried adapting T to "extend" the special trait std::any::Any but still couldn't figure out how to do this.

dhardy
  • 11,175
  • 7
  • 38
  • 46
  • 2
    This is commonly referred to as *downcasting*, so this is likely a duplicate of http://stackoverflow.com/q/33687447/155423. – Shepmaster Dec 11 '15 at 19:06
  • You already said that. My bad for not realising the significance of the `as_any()` function: it's the only way to get a reference to the trait object, *seen as a `&S`, not `&T`*. Confusing. – dhardy Dec 11 '15 at 19:12
  • Sorry, so many people ask duplicate questions without searching, so I just point them out. If you know it's not a duplicate, **say so** in your question and explain *why* it isn't; linking to the not-a-duplicate is even better. Otherwise, we don't know why it's not different, and it's more likely to be marked as a duplicate. – Shepmaster Dec 11 '15 at 19:22
  • Yes, it's a duplicate. The problem is, I saw the answer *the first is to use `Any`*, and tried to use the library docs. They're rather inspecific and use `Any` in a different way (as a bound on a generic type). – dhardy Dec 11 '15 at 20:50
  • 1
    I agree that those docs aren't the greatest. I think I saw a minor lie in them, which I'm working on fixing :-) Rust is pretty happy to improve though, so I'd encourage you to open an issue with some suggestions on how to improve the docs. – Shepmaster Dec 11 '15 at 21:09

0 Answers0