error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable
535 | let conn = &mut self.connections[tok.into()];
| ---------------- mutable borrow occurs here
545 | self.dispatch_by_type(conn.socket(), tok, poll);
| | |
| | mutable borrow later used here
| immutable borrow occurs here
som related function definition:
fn dispatch_by_type(&self, stream: &Stream, tok: Token, poll: &Poll) -> std::io::Result<()>
pub fn socket(&self) -> &Stream
conn.socket() would't get the same complie error in
Side note: it'd be better if you copied the code in question, not made a screenshot, so that we can check it ourselves.
The problem is not with
conn.socket itself. Error message shows you three parts:
- Place where
conn is created. There, it's shown that you take an exclusive borrow of
self's field and store it in
conn is - indirectly - an exclusive borrow of
- Place where
self is borrowed again - in
- Place where the first borrow of
self (stored in
conn) is used.
The past part happens after the second borrow of
self (because method arguments are evaluated after the receiver), so
conn (and therefore
&mut self) is forced to be alive at the point when
&self is created. Exclusive reference coexisting with any other one is an error.
match, however, you doesn't touch
self at all - you only use
conn, and that's obviously valid.
Based on the signatures you noted, you can probably do...
let idx = tok.into();
let conn = &mut self.connections[idx];
// Do whatever you need `conn` to be a `&mut` for here, then...
// ...borrow anew as a `&`
let conn = &self.connections[idx];
self.dispatch_by_type(conn.socket(), tok, poll);
make sense. I got it. Apprecited!
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.