【发布时间】:2015-10-31 15:50:43
【问题描述】:
我不明白 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 的示例。
【问题讨论】:
-
stackoverflow.com/questions/30154541/… 或 stackoverflow.com/questions/31331308/… 的重复项?如果你不同意,你应该edit你的问题来澄清为什么它不是重复的。
-
@Shepmaster 是的,你是对的。这是类似的问题。但是你的问题是关于函数和字符串的。我询问了方法和字符串字段。我也遇到了生命周期问题,我尝试使用
'a来解决它。 @lllogiq 向我展示了如何在没有它的情况下连接字符串字段。
标签: string struct rust string-concatenation