0

I'm being unable to compile the following:

pub trait Symbol : ToString {
    fn callee(self: &Rc<Self>) -> Option<Rc<dyn Symbol>> {
        None
    }
}

Taking Rc parameter causes the error...

E0038) the trait symbols::Symbol cannot be made into an object

everywhere Symbol is used, including in that function declaration.

It does work if I take &self instead of self: &Rc<Self>, however I've some functions that really need to take this Rc. Any idea of what to do?

  • 1
    Does this answer your question? [The trait cannot be made into an object](https://stackoverflow.com/questions/45116984/the-trait-cannot-be-made-into-an-object) – Jmb Nov 03 '21 at 10:20
  • @Jmb This seems to be about a field, while I'm dealing with a trait's method (dynamic dispatch or late binding). –  Nov 03 '21 at 10:22
  • 2
    See also https://doc.rust-lang.org/reference/items/traits.html#object-safety – Jmb Nov 03 '21 at 10:23
  • 1
    Note that it should work with `fn callee (self: Rc)` – Jmb Nov 03 '21 at 10:24
  • @Jmb I've just tried it, the only problem is that doing this will move ownership to the first call to `callee()`, but looks like that is what I can do for now. Thanks! –  Nov 03 '21 at 10:26
  • 2
    You can clone if you don't want to move ownership (cloning an `Rc` is cheap whatever the inner type is). – Jmb Nov 03 '21 at 10:28

1 Answers1

0

Notice this error message:

error[E0307]: invalid `self` parameter type: Rc<(dyn Symbol + 'static)>
 --> src/lib.rs:3:21
  |
3 |     fn callee(self: Rc<dyn Symbol>) -> Option<Rc<dyn Symbol>> {
  |                     ^^^^^^^^^^^^^^
  |
  = note: type of `self` must be `Self` or a type that dereferences to it
  = help: consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one of the previous types except `Self`)

It should be a Rc<Self>, it makes not much sense of using &Rc since Rc is cheap to clone.

use std::rc::Rc;
pub trait Symbol : ToString {
    fn callee(self: Rc<Self>) -> Option<Rc<dyn Symbol>> {
        None
    }
}

Playground

Cerberus
  • 8,879
  • 1
  • 25
  • 40
Netwave
  • 40,134
  • 6
  • 50
  • 93