0

I was surprised to see the smart pointer RefCell can mutate any type of data as I expect to mutate even const. Why const data cannot be mutated via smart pointers? If I considered the const can never be changed then why the attempt to modify const data executed successfully?

 const NAME : RefCell<&str> = RefCell::new("XYZ");
    println!("The const NAME is: {}",*NAME.borrow_mut());

 *NAME.borrow_mut() = "abc";
    println!("The mutated NAME is: {}",*NAME.borrow());

I exactly want to know why the const data is not modified even the compiler executed the code successfully. I expect the compiler will stop me from doing that modification but actually it didn't? Here is the output,

The name is: XYZ
The mutated name is: XYZ
  • Atleast compiler need to warn us that we r if creating an instance of const,I got it, const are values not memory space actually, I just want to know why compiler says nothing about that??? – Fawad Ahmed May 26 '20 at 11:13
  • For what it's worth, `clippy` does warn (and in fact gives an error) when a constant has interior mutability. – SCappella May 26 '20 at 11:41
  • `RefCell` is not _quite_ a smart pointer => it does not allocate or deallocate memory. – Matthieu M. May 26 '20 at 13:09

0 Answers0