首页 > 解决方案 > 抽象函数接收和返回 Rc

问题描述

我无法编译以下内容:

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

Rc参数会导致错误...

E0038)symbols::Symbol无法将特征制成对象

无处不Symbol在,包括在该函数声明中。

如果我使用&self而不是 ,它确实有效self: &Rc<Self>,但是我有一些真正需要使用这个 Rc 的功能。知道该怎么做吗?

标签: rust

解决方案


请注意此错误消息:

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`)

它应该是Rc<Self>,它没有太大的使用意义,&Rc因为Rc克隆起来很便宜。

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

操场


推荐阅读