Mutable and immutable borrow at the same time?


I saw this code in an example for using tokio.

if let Some(n) = buf.as_ref()[4…].iter().position(|b| *b == b’\n’) {
// remove the serialized frame from the buffer.
let line = buf.split_to(n + 4);

        // Also remove the '\n'

        // Deserialize the request ID
        let request_id = io::Cursor::new(&line[0..4]).get_u32::<BigEndian>();

        // Turn this data into a UTF string and return it in a Frame.
        return match str::from_utf8(&line.as_ref()[4..]) {
            Ok(s) => Ok(Some((request_id as RequestId, s.to_string()))),
            Err(_) => Err(io::Error::new(io::ErrorKind::Other, "invalid string")),

buf.as_ref() is a immutable borrow and buf.spit() is a mutable borrow, what am i missing here?


The expression above returns an Option<usize> which does not depend on the lifetime of buf. In other words, buf is no longer borrowed at the end of this expression and can subsequently be borrowed mutably.


Ah that makes sense, thanks.