4

I have defined these:

struct MyStruct<T> { /* ... */ }

trait MyTrait: Any { /* ... */ }

impl<T> MyTrait for MyStruct<T> { /* ... */ }

Is it possible to downcast Rc<RefCell<MyTrait>> to Rc<RefCell<MyStruct<T>>> (in the context of a function generic on T)?

fn some_fn<T>(h: &HashMap<String, Rc<RefCell<MyTrait>>>, key: &str) -> Rc<RefCell<MyStruct<T>>> {
    let x: Rc<RefCell<MyTrait>> = h.get(key).unwrap().clone();
    /* what goes here ??? */ (x)
}
user1411900
  • 384
  • 4
  • 14
  • I believe your question is answered by the answers of [How to get a struct reference from a boxed trait?](https://stackoverflow.com/q/33687447/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jun 11 '18 at 21:39
  • @Shepmaster: I actually meant to return the downcasted reference, so getting a reference to MyStruct with non-static lifetime is not sufficient. – user1411900 Jun 12 '18 at 04:57
  • This is surprisingly difficult, because you can't cross-cast from `Rc>` to `Rc>`, and you can't use an `as_any` method on `MyTrait` because `Rc>` isn't a valid receiver. `transmute` would appear to be your only option. – trent Jun 12 '18 at 13:45
  • But what should `some_fn` do when the `HashMap` contains an `Rc>`? You have to account for failure somehow (e.g. by panicking, or returning an `Option`). – trent Jun 12 '18 at 13:48
  • 1
    @trentcl: if the type does not match, it's fine to just panic. Regarding transmuting, is there a recommended way to do that? Are they bit-compatible? – user1411900 Jun 13 '18 at 17:33

0 Answers0