我无法理解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
}
}
运行时出错:
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.
我从Rust书中读到this chapter。我尝试连接代码示例中的字符串,但编译器说它不是字符串。
我在线搜索,但没有 Rust 1.3 的例子。
答案 0 :(得分:4)
You try to concatenate two pointers to strings, but this is not how string concatenation works in Rust. The way it works is that it consumes the first string (you have to pass that one in by value) and returns the consumed string extended with the contents of the second string slice.
Now the easiest way to do what you want is:
fn get_data(&self, word: &str) -> String {
format!("{}{}{}", &self.field_1, &self.field_2, word)
}
Note that will also create a new owned String, because it is impossible to return a String reference of a String from the scope that created the String – it will be destroyed at the end of the scope, unless it is returned by value.