我可以用 Rust 编写一个不可变变量

Fra*_*dom 1 immutability ownership mutability rust

  let mut a = Box::new("123".to_string());
  let b = Box::new( &mut a);

  b.push('4');

  assert_eq!( "1234", b.as_str());

  // lets see the types:
  // let x001: Box<&mut Box<String>> = b;
  // let x001:&mut Box<String> = *b;
  // let x001:Box<String> = **b;
  // let x001:String = ***b;
  // let x001:str = ****b;

  let c = Box::new("456".to_string());

  **b = c;

  b.push('9');
  (*b).push('9');
  (**b).push('9');
  (***b).push('9');
  // (****b).push('9'); // no method named `push` found for type `str` in the current scope

  // c.push( 'a'); // cannot mutate immutable variable `c`

  assert_eq!( "4569999", b.as_str());

  ***b = "abcd".to_string();

  b.push('9');

  assert_eq!( "abcd9", b.as_str());
Run Code Online (Sandbox Code Playgroud)

变量 c 被隐式声明为不可变,但将其放入框中后,它可以因为所有权转移而发生变化?

但最终这意味着我们可以改变每个不可变变量。

有人可以解释一下吗?

caf*_*e25 5

(Im-)可变性是绑定的属性,而不是值。

let c = String::from("c");
let mut a = c;
a.push_str("whatever");
Run Code Online (Sandbox Code Playgroud)

也有效。

你所做的基本上是一样的:

**b = c;
Run Code Online (Sandbox Code Playgroud)

将 的值移动到存储在isc中的可变引用所指向的位置,这是一个可变绑定。ba