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());

变量c被隐式声明为不可变的,但在将其放入框中后,它是否会因为所有权转移而发生Mutations ?

但最终,这将意味着我们可以改变所有不变的变量.

有谁能解释一下吗?

推荐答案

(IM-)可变性是绑定的属性,而不是值.

let c = String::from("c");
let mut a = c;
a.push_str("whatever");

也很管用.

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

**b = c;

将值c移到b中存储的可变引用指向的位置,即a,这是一个可变绑定.

Rust相关问答推荐

将大小为零的类型实例存储到空指针中

为什么我可以跟踪以前borrow 过的变量?房主在哪里?

为什么实例方法可以像Rust中的静态方法一样被调用?

在使用#[NO_STD]时,如何在Rust中收到紧急消息?

如何循环遍历0..V.len()-1何时v可能为空?

为什么这个变量不需要是可变的?

如果变量本身不是None,如何返回;如果没有,则返回None&Quot;?

如何将带有嵌套borrow /NLL 的 Rust 代码提取到函数中

std mpsc 发送者通道在闭包中使用时关闭

在 Rust 中忽略 None 值的正确样式

缺失serde的字段无法设置为默认值

不安全块不返回预期值

类型判断模式匹配panic

Rust 中的方法调用有什么区别?

特征中定义的类型与一般定义的类型之间的区别

无法理解 Rust 对临时值的不可变和可变引用是如何被删除的

在 Rust 中,将可变引用传递给函数的机制是什么?

判断 is_ok 后重用结果

有没有办法使用 NASM 语法进行内联汇编?

为什么这个 Trait 无效?以及改用什么签名?