[ NEWBIE ] Why can i mutate data that is returned as immutable

Hi Everyone!

To moderator, plz forgive me if i am asking too many questions, i am new to rust (3 days so far) and i am trying to wrap my head about it, plz note that i do search before i post, and i only ask questions, when i don't fully understand the reason why!

Thank in advance :slight_smile:

Here i am trying to understand, why i can mutate data, that i returned as &str and why &mut str is not enforced by the compiler

use std::sync::Mutex;

#[derive(Debug)]
struct Actor {
    name: Mutex<String>,
}

impl Actor {
    fn get_mut_ref(&mut self) -> &str {
        self.name.get_mut().unwrap()
    }
}

fn main() {
    let mut actor = Actor {
        name: Mutex::new("abcd".into())
    };

    let mut p_ref = actor.get_mut_ref();

    dbg!(p_ref);

    p_ref = "defg";

    dbg!(p_ref);
}

You don't mutate &str - the data behind the reference stay the same. You reassign the variable to another &str, which points to another block of data.

1 Like

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.