{"id":1187,"hash":"c83224720b6e1f2d20e3778a4b9ec712e354686471c9cedbb8fae0b929be51de","pattern":"Cannot borrow in a Rc as mutable","full_message":"First of all I'm new with Rust :-)\n\nThe problem:\nI want to create a module called RestServer that contain the methods ( actix-web ) to add routes and start the server.\n\nstruct Route\n{\n   url: String,\n   request: String,\n   handler: Box<dyn Fn(HttpRequest) -> HttpResponse>\n}\n\nimpl PartialEq for Route {\n   fn eq(&self, other: &Self) -> bool {\n     self.url == other.url\n   }\n}\n\nimpl Eq for Route {}\n\nimpl Hash for Route {\n   fn hash<H: Hasher>(&self, hasher: &mut H) {\n      self.url.hash(hasher);\n   }\n}\n\nthis is the route structure, this structure containe the the route url, the request type ( GET, POST etc ) and hanlder is the function that have to catch the request and return a HTTPResponse\n\npub struct RestServer\n{\n   scopes: HashMap<String, Rc<HashSet<Route>>>,\n   routes: HashSet<Route>,\n   host: String,\n}\n\nimpl RestServer {\n\n   pub fn add_route(self, req: &str, funct: impl Fn(HttpRequest) -> HttpResponse + 'static,\n                 route: &str, scope: Option<&str>) -> RestServer\n   {\n       let mut routes_end = self.routes;\n       let mut scopes_end = self.scopes;\n       let url = self.host;\n       let route = Route {\n          url: String::from(route),\n          request: String::from(req),\n          handler: Box::new(funct)\n    };\n\n    if let Some(x) = scope {\n        if let Some(y) = scopes_end.get(x) {\n            let mut cloned_y = Rc::clone(y);\n            cloned_y.insert(route);\n            scopes_end.insert(String::from(x), cloned_y);\n        }else {\n            let mut hash_scopes = HashSet::new();\n            hash_scopes.insert(route);\n            scopes_end.insert(String::from(x), Rc::new(hash_scopes));\n        }\n    } else {\n        routes_end.insert(route);\n    }\n\n    RestServer {\n        scopes: scopes_end,\n        routes: routes_end,\n        host: String::from(url)\n    }\n  }\n\nthe latest code is the implementation of RestServer. \nThe most important part is the add_route function, this function receive as paramente the route that is a string, the function handler, the request string and the scope.\nFirst i create the route object.\nI check if the scope exist into the HashMap, if yes i have to take the actual scope and update the HashSet.\n\nWhen i build the code i get the following error\n\n   error[E0596]: cannot borrow data in an `Rc` as mutable\n   --> interface/src/rest/mod.rs:60:17\n   |\n60 |                 cloned_y.insert(route);\n   |                 ^^^^^^^^ cannot borrow as mutable\n   |\n   = help: trait `DerefMut` is required to modify through a dereference, but it is not \n     implemented for `std::rc::Rc<std::collections::HashSet<rest::Route>>`\n\nI know that the compiler give me some help but honestly i have no idea how to do that or if i can do with some easy solution.\nAfter a large search in google i found a solution in RefCell, but is not so much clear\n\nThanks in advance for your help","ecosystem":"cargo","package_name":"borrowing","package_version":null,"solution":"You cannot borrow a reference-counting pointer as mutable; this is because one of the guarantees it provides is only possible if the structure is read-only.\n\nYou can, however, get around it, but it will require some signature changes.\n\nEnter interior mutability\n\nInterior mutability is a concept you may know from other programming languages in the form of mutexes, atomics and synchronization primitives. In practice, those structures allow you to temporarily guarantee that you are the only accessor of a given variable.\n\nIn Rust, this is particularly good, as it allows us to extract a mutable reference to an interior member from a structure that only requires immutable references to itself to function. Perfect to fit in Rc.\n\nDepending on what you need for your needs, you will find the Cell and RefCell structures to be exactly what you need for this. These are not thread-safe, but then again, neither is Rc so it's not exactly a deal-breaker.\n\nIn practice, it works very simply:\n\nlet data = Rc::new(RefCell::new(true));\n{\n  let mut reference = data.borrow_mut();\n  *reference = false;\n}\nprintln!(\"{:?}\", data);\n\nplayground\n\n(If you ever want the threaded versions, Arc replaces Rc and Mutex or RwLock replaces Cell/RefCell)","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/58599539/cannot-borrow-in-a-rc-as-mutable","votes":23,"created_at":"2026-04-19T04:52:34.050277+00:00","updated_at":"2026-04-19T04:52:34.050277+00:00"}