2015-10-30 32 views
1

我无法理解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的例子。

+2

重复的http://stackoverflow.com/questions/30154541/how-do-i-concatenate-strings或http://stackoverflow.com/questions/31331308/what-is-the-standard-way-to -concatenate串?如果你不同意,你应该[编辑]你的问题来澄清为什么它不是重复的。 – Shepmaster

+0

@Shepmaster是的,你是对的。这是类似的问题。但是你的问题询问函数和字符串。我询问了方法和字符串字段。我也有一生的问题,我尝试用''a'解决它。 @llogiq向我展示了如何连接没有它的字符串字段。 –

回答

3

您尝试将两个指针连接到字符串,但这不是字符串连接在Rust中的工作原理。它的工作方式是它消耗第一个字符串(您必须通过值传入该字符串)并返回扩展了第二个字符串切片内容的消耗字符串。

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

fn get_data(&self, word: &str) -> String { 
    format!("{}{}{}", &self.field_1, &self.field_2, word) 
} 

注意,也将创造一个新的拥有字符串,因为它是不可能返回从创建的范围一串一串的参考字符串 - 它将在范围的末尾销毁,除非它是按值返回的。

+0

为什么你认为这个问题不是上面评论中可能的问题的重复? – Shepmaster

+0

@llogiq现在我明白了。谢谢。 –

+0

@Shepmaster,我一定忽略了他们。 – llogiq

相关问题