【问题标题】:Why immutable string can call String::add(mut self, other: &str) [duplicate]为什么不可变字符串可以调用 String::add(mut self, other: &str) [重复]
【发布时间】:2021-01-12 11:07:36
【问题描述】:

在 stdlib 中 字符串.rs:

impl Add<&str> for String {
    type Output = String;

    #[inline]
    fn add(mut self, other: &str) -> String {
        self.push_str(other);
        self
    }
}


let s1 = String::from("tic");
let s2 = String::from("tac");

let s = s1 + &s2;// it works

s1在这里是不可变的,但是 Add::add(mut self, other: &str) 是mut,我只是想知道为什么。

【问题讨论】:

  • AFAIK,mut self 与 &amp;mut self 不同,您的变量只能在第二种情况下是可变的

标签: rust move-semantics


【解决方案1】:

当您在串联中使用s1 时,您借用并使用了它。如果您尝试在行后打印s1 let s = s1 + &amp;s2;// it works, 会出现错误,因为它是在move之后使用的:

3 |     let s1 = String::from("tic");
  |         -- move occurs because `s1` has type `std::string::String`, which does not implement the `Copy` trait
...
6 |     let s = s1 + &s2;// it works
  |             -- value moved here
7 |     println!("{}{}{}",s,s1,s2);
  |                         ^^ value borrowed here after move

s1 不需要是可变的,因为变量永远不会发生变异,数据被移动并变异为变量s。

【讨论】:

    【解决方案2】:
    s1 is immutable here
    

    不完全是。 s1 绑定是不可变的,但由于add 拥有它所绑定的值,它可以用它做它想做的事情(包括改变它)。由于您无法再访问该值,因此您无法观察到变化,这对您没有任何影响。

    这与肉类世界没有什么不同:如果你借东西给某人并且他们有你的许可修改它,那么他们可能会这样做,但如果你给予一些东西给某人,他们是否修改它不再是你的事了。

    正如 Simson 所说,如果您在添加后尝试重用 s1,编译器将拒绝您的代码。

    【讨论】:

      猜你喜欢
      • 2014-11-29
      • 2017-08-10
      • 2016-03-13
      • 2017-05-02
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多