为什么不可变字符串可以调用 String::add(mut self, other: &str) [英] Why immutable string can call String::add(mut self, other: &str)

查看:55
本文介绍了为什么不可变字符串可以调用 String::add(mut self, other: &str)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

stdlibstring.rs:

In stdlib string.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,我只是想知道为什么.

s1 is immutable here, but Add::add(mut self, other: &str) is mut, I just want to know why.

推荐答案

当您在串联中使用 s1 时,您可以借用和使用它.如果您尝试在该行之后打印 s1let s = s1 + &s2;//有效,会报错,因为是move后用的:

You borrow and consume s1 when you use it in the concatenation. If you try to print s1 after the line let s = s1 + &s2;// it works, there will be an error because it is used after 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.

s1 does not need to be mutable as the variable is never mutated the data is moved and mutated to the variable s.

这篇关于为什么不可变字符串可以调用 String::add(mut self, other: &amp;str)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆