我无法理解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.
我从锈书阅读this chapter。我尝试像代码示例中那样连接字符串,但编译器说它不是字符串。
我在网上搜索,但没有Rust 1.3的例子。
重复的http://stackoverflow.com/questions/30154541/how-do-i-concatenate-strings或http://stackoverflow.com/questions/31331308/what-is-the-standard-way-to -concatenate串?如果你不同意,你应该[编辑]你的问题来澄清为什么它不是重复的。 – Shepmaster
@Shepmaster是的,你是对的。这是类似的问题。但是你的问题询问函数和字符串。我询问了方法和字符串字段。我也有一生的问题,我尝试用''a'解决它。 @llogiq向我展示了如何连接没有它的字符串字段。 –