2015-10-30 34 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

相關問題