如何将两个字符串字段与另一个字符串连接起来?

Har*_*ari 1 string struct string-concatenation rust

我不明白 Rust 如何处理字符串。我创建了一个带有两个字符串字段和一个方法的简单结构。此方法连接两个字段和参数中的字符串。我的代码:

fn main() {
    let obj = MyStruct {
        field_1: "first".to_string(),
        field_2: "second".to_string(),
    };

    let data = obj.get_data("myWord");
    println!("{}",data);
}

struct MyStruct {
    field_1: String,
    field_2: String,
}

impl MyStruct {
    fn get_data<'a>(&'a self, word: &'a str) -> &'a str {
        let sx = &self.field_1 + &self.field_2 + word;
        &* sx
    }
}
Run Code Online (Sandbox Code Playgroud)

运行时出现错误:

src\main.rs:18:18: 18:31 error: binary operation `+` cannot be applied to type `&collections::string::String` [E0369]
src\main.rs:18         let sx = &self.field_1 + &self.field_2 + word;
                                ^~~~~~~~~~~~~
src\main.rs:19:10: 19:14 error: the type of this value must be known in this context
src\main.rs:19         &* sx
                        ^~~~
error: aborting due to 2 previous errors
Could not compile `test`.

To learn more, run the command again with --verbose.
Run Code Online (Sandbox Code Playgroud)

我读了Rust 书中的这一章。我尝试像代码示例中那样连接字符串,但编译器说它不是字符串。

我在网上搜索,但没有Rust 1.3的示例。

llo*_*giq 5

您尝试连接两个指向字符串的指针,但这不是 Rust 中字符串连接的工作方式。它的工作方式是它消耗第一个字符串(您必须按值传递该字符串)并返回使用第二个字符串切片的内容扩展的消耗字符串。

\n\n

现在,做你想做的事的最简单方法是:

\n\n
fn get_data(&self, word: &str) -> String {\n    format!("{}{}{}", &self.field_1, &self.field_2, word)\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

请注意,还将创建一个新的拥有的 String,因为不可能从创建 String \xe2\x80\x93 的范围返回 String 的 String 引用,它将在范围末尾被销毁,除非返回按价值。

\n