Reference variable with explicit immutable reference type specified accepts both mutable and immutable borrow?

⚓ rust    📅 2025-05-23    👤 surdeus    👁️ 3      

surdeus

Warning

This post was published 37 days ago. The information described in this article may have changed.

I noticed that a reference variable with type explicitly specified as immutable reference can accept both mutable as well as immutable borrow. Like

fn main() {
    let s1 = String::from("Hello");
    let sref: &str = &s1; //This is ok as expected
    println!("{sref}");
}

fn main() {
    let mut s1 = String::from("Hello");
    let sref: &str = &mut s1; // This is ok too!!
    println!("{sref}");
}

In both cases, the type of sref is &str and cannot call any str methods, that take &mut self as argument. Same holds true for simple types like i32, u32 etc as well. I was expecting only something like below to be possible: i.e only mutable reference type should be able to mutably borrow a value.

let sref : &mut str = &mut s1;

Why is this allowed and what is the purpose?

Thanks!

3 posts - 3 participants

Read full topic

🏷️ rust_feed