'Are string literals immutable

I am following the Rust book to learn Rust and currently learning about ownership. Here it mentions,

We’ve already seen string literals, where a string value is hardcoded into our program. String literals are convenient, but they aren’t suitable for every situation in which we may want to use text. One reason is that they’re immutable.

The code below runs without any problem, Here I changed the value of a, if immutability can be changed whats the problem stated there?

fn main() {
   let mut a = "Hello";
   println!("{}", a);
   a = " World";
   println!("{}",a);
 }


Solution 1:[1]

The executable binary produced by the rust compiler contains the string literals "Hello" and "World" in the read-only data section rodata.

$ cargo build --release
$ readelf -x .rodata target/release/demo | grep Hello
  0x0003c000 48656c6c 6f000000 0a576f72 6c640000 Hello....World..

Because these literals are placed in an immutable section, the operating system prohibits modifying them.

fn main() {
    let mut a = "Hello";
    println!("{}", a);

    unsafe { (a.as_ptr() as *mut u8).write(42) };
    println!("{}", a);
}
$ cargo run
Hello
Segmentation fault

However, the variable a is of type &str, so a pointer to a string slice, and it lives on the stack. Therefore, it is totally valid for a to first point to the address of "Hello", and then to the address of "World".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1