如何连接以下类型组合:

  • strstr
  • Stringstr
  • StringString

推荐答案

连接字符串时,需要分配内存来存储结果.最简单的开始是String&str:

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    owned_string.push_str(borrowed_string);
    println!("{}", owned_string);
}

在这里,我们拥有一个可以变异的字符串.这是有效的,因为它可能允许我们重用内存分配.StringString也有类似的情况,比如&Stringcan be dereferenced as &str.

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    owned_string.push_str(&another_owned_string);
    println!("{}", owned_string);
}

在此之后,another_owned_string保持不变(注意mut限定符).还有另一个变体consumesString相同,但不要求它是可变的.这是一个implementation of the Add trait,以String为左侧,&str为右侧:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let new_owned_string = owned_string + borrowed_string;
    println!("{}", new_owned_string);
}

请注意,拨打+后,owned_string将不再可用.

如果我们想制作一个新的字符串,让两者都保持不变呢?最简单的方法是使用format!:

fn main() {
    let borrowed_string: &str = "hello ";
    let another_borrowed_string: &str = "world";
    
    let together = format!("{}{}", borrowed_string, another_borrowed_string);

    // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
    // let together = format!("{borrowed_string}{another_borrowed_string}");

    println!("{}", together);
}

请注意,这两个输入变量都是不可变的,因此我们知道它们不会被触碰.如果我们想对String的任意组合做同样的事情,我们可以利用String也可以格式化的事实:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    let together = format!("{}{}", owned_string, another_owned_string);

    // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
    // let together = format!("{owned_string}{another_owned_string}");
    println!("{}", together);
}

不过你不需要用format!.您可以 Select clone one string并将另一个字符串附加到新字符串:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let together = owned_string.clone() + borrowed_string;
    println!("{}", together);
}

Note-我所做的所有类型规范都是多余的-编译器可以推断出这里使用的所有类型.我添加这些问题只是为了让新Rust 的人明白,因为我希望这个问题会受到该群体的欢迎!

Rust相关问答推荐

为什么铁 rust S的默认排序功能比我对小数组的 Select 排序稍微慢一些?

在Rust中判断编译时是否无法访问

Rust,如何从 Rc> 复制内部值并返回它?

为什么编译器看不到这个 `From` impl?

为什么某些类型参数仅在特征边界中使用的代码在没有 PhantomData 的情况下进行编译?

更新 rust ndarray 中矩阵的一行

如何保存指向持有引用数据的指针?

‘&T as *const T as *mut T’ 在 ‘static mut’ 项目中合适吗?

为什么会出现无法移出可变引用后面的 `self.x`错误?

为什么我可以同时传递可变和不可变引用?

只有一个字符被读入作为词法分析器的输入

是否有适当的方法在参考 1D 中转换 2D 数组

为实现特征的所有类型实现显示

为什么分配对变量的引用使我无法返回它

翻转布尔值的最快方法

Rust 宏:根据参数数量重复 n 次,而不使用实际参数

我是否可以在 Rust 的 MacroMatch 中使用逗号以外的分隔符?

我在 Rust 中的 for 循环变体之间有什么区别?

允许使用事件循环扩展(超出 crate )实现

根据rust函数中的泛型 Select 常量