簡體   English   中英

添加兩個字符串時如何修復不匹配的類型?

[英]How to fix mismatched types when adding two Strings?

使用&str的列表輸入,我試圖創建一個包含基於輸入的諺語的String

而不是String::from我也嘗試了.to_string()但這似乎沒有幫助。

pub fn build_proverb(list: &[&str]) -> String {
    let mut string = String::from(format!("For want of a {} the {} was lost.\n", list[0], list[1]));

    if list.len() > 2 {
        (3..list.len() + 1).map(|x| string = string + String::from(format!("For want of a {} the {} was lost.\n", list[x], list[x-1])));
    }

    string = string + &(format!("And all for the want of a {}.", list[0])).to_string();

    return string.to_string();
}

錯誤是:

error: mismatched types expected &str, found struct 'std::string::String'.

這是在String::from(format!("For want of a {} the {} was lost.\\n", list[x], list[x-1]))行上。

讓我感到困惑的是,我將一個String添加到一個String ——為什么它需要一個&str

format! 已經返回一個String ,所以不需要String::from(format!(...)) ,它也是一個錯誤,因為它需要一個&str ,而不是format!返回的String format! .

你還會在 lambda 中得到一個錯誤:

string = string + String::from(format!(...))

...即使您刪除String::from ,因為不可能像這樣添加兩個String ,但是可以添加一個String和一個&str ,所以我認為您應該像這樣借用:

string = string + &format!(...)

這一行也是如此:

string = string + &(format!("And all for the want of a {}.", list[0])).to_string();

此外,您對map的使用實際上不會為范圍的每個元素執行 lambda。 它只會創建一個Map iterator ,你必須用一個循環迭代它才能真正執行 lambda,所以你也可以迭代范圍本身並在循環中修改你的字符串。

我也不太確定為什么在您可以返回string本身時返回string.to_string()


我也認為你的范圍內有一個錯誤,所以在解決這個問題之后,我最終得到了這個:

fn do_it(list: Vec<&str>) -> String {
    let mut string = format!("For want of a {} the {} was lost.\n", list[0], list[1]);

    // BTW, you don't need this `if` statement because empty ranges, like `2..2`, are perfectly fine
    if list.len() > 2 {
        // These ranges do not include `list.len()`, so your program won't panic, because this index doesn't exist
        for x in 2 .. list.len() {
            string += &format!("For want of a {} the {} was lost.\n", list[x], list[x-1])
        }
    }

    string + &format!("And all for the want of a {}.", list[0])  // Return the result of concatenation
}

fn main() {
    let list = vec!["something", "test", "StackOverflow"];
    let result = do_it(list);

    println!("The result is: {}", result)
}

輸出(它有效,但你的帖子沒有說明它應該輸出什么,所以我不能說它是否是正確的結果):

The result is: For want of a something the test was lost.
For want of a StackOverflow the test was lost.
And all for the want of a something.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM