无法在 Rc 中作为可变借用。

16
首先,我是 Rust 的新手 :-)
问题: 我想创建一个名为 RestServer 的模块,包含添加路由和启动服务器的方法(使用 actix-web)。
struct Route
{
   url: String,
   request: String,
   handler: Box<dyn Fn(HttpRequest) -> HttpResponse>
}


impl PartialEq for Route {
   fn eq(&self, other: &Self) -> bool {
     self.url == other.url
   }
}

impl Eq for Route {}

impl Hash for Route {
   fn hash<H: Hasher>(&self, hasher: &mut H) {
      self.url.hash(hasher);
   }
}

这是路由结构,该结构包含路由URL、请求类型(GET、POST等),以及处理程序是必须捕获请求并返回HTTP响应的函数

pub struct RestServer
{
   scopes: HashMap<String, Rc<HashSet<Route>>>,
   routes: HashSet<Route>,
   host: String,
}

impl RestServer {

   pub fn add_route(self, req: &str, funct: impl Fn(HttpRequest) -> HttpResponse + 'static,
                 route: &str, scope: Option<&str>) -> RestServer
   {
       let mut routes_end = self.routes;
       let mut scopes_end = self.scopes;
       let url = self.host;
       let route = Route {
          url: String::from(route),
          request: String::from(req),
          handler: Box::new(funct)
    };

    if let Some(x) = scope {
        if let Some(y) = scopes_end.get(x) {
            let mut cloned_y = Rc::clone(y);
            cloned_y.insert(route);
            scopes_end.insert(String::from(x), cloned_y);
        }else {
            let mut hash_scopes = HashSet::new();
            hash_scopes.insert(route);
            scopes_end.insert(String::from(x), Rc::new(hash_scopes));
        }
    } else {
        routes_end.insert(route);
    }

    RestServer {
        scopes: scopes_end,
        routes: routes_end,
        host: String::from(url)
    }
  }

最新的代码实现了RestServer。 最重要的部分是add_route函数,该函数接受路由字符串、函数处理程序、请求字符串和作用域作为参数。 首先创建路由对象。 我检查哈希映射中是否存在作用域,如果是,则必须获取实际作用域并更新哈希集。

构建代码时出现以下错误

   error[E0596]: cannot borrow data in an `Rc` as mutable
   --> interface/src/rest/mod.rs:60:17
   |
60 |                 cloned_y.insert(route);
   |                 ^^^^^^^^ cannot borrow as mutable
   |
   = help: trait `DerefMut` is required to modify through a dereference, but it is not 
     implemented for `std::rc::Rc<std::collections::HashSet<rest::Route>>`

我知道编译器会给我一些帮助,但说实话,我不知道如何做或者是否可以用一些简单的解决方案来完成。 在谷歌上进行了大量搜索后,我在RefCell中找到了一个解决方案,但并不是很清晰。

提前感谢您的帮助。

1个回答

30

您不能将引用计数指针作为可变引用借用,因为它提供的保证之一仅在结构体只读时才可能实现。

但是,您可以绕过这个问题,但它需要进行一些签名更改。

进入内部可变性

内部可变性是您可能从其他编程语言中了解到的概念,它以互斥、原子和同步原语的形式存在。在实践中,这些结构允许您暂时保证您是给定变量的唯一访问者。

在Rust中,这非常好,因为它允许我们从一个只需要自身不可变引用来运行的结构中提取对内部成员的可变引用。非常适合Rc

根据您的需求,您会发现CellRefCell结构正是您所需要的。它们不是线程安全的,但是,Rc也不是,因此这不是一个硬伤。

在实践中,它非常简单:

let data = Rc::new(RefCell::new(true));
{
  let mut reference = data.borrow_mut();
  *reference = false;
}
println!("{:?}", data);

代码演示

(如果您需要线程安全的版本,Arc 可以替换 RcMutexRwLock 可以替换 Cell/RefCell)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接