Rust 如何在添加两个字符串时修复不匹配的类型?

Rust 如何在添加两个字符串时修复不匹配的类型?,rust,Rust,使用&str的列表输入,我试图创建一个字符串,其中包含一个基于输入的谚语 除了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])

使用
&str
的列表输入,我试图创建一个
字符串
,其中包含一个基于输入的谚语

除了
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();
}
错误是:

错误:应为不匹配的类型&str,找到结构“std::string::string”。
这在
String::from(format!({}因为缺少一个{},所以{}丢失了。\n',list[x],list[x-1])

让我困惑的是,我正在将
字符串添加到
字符串
-为什么它需要
&str

格式
,因此不需要
字符串::from(format!(…)
,这也是一个错误,因为它需要
&str
,而不是
格式返回的
字符串

您还将在lambda中得到一个错误:

string = string + String::from(format!(...))
…即使您从
中删除了
字符串::,因为这样添加两个
字符串
是不可能的,但是可以添加一个
字符串
和一个
&str
,所以我认为您应该这样借用:

string = string + &format!(...)
这一行也是如此:

string = string + &(format!("And all for the want of a {}.", list[0])).to_string();
此外,使用
map
实际上不会对范围的每个元素执行lambda,您必须使用循环进行迭代,以使其实际执行lambda,因此您也可以在范围本身上进行迭代,并修改循环中的字符串

我也不太清楚为什么要返回
string.to_string()
,而您本可以返回
string
本身


我还认为您的范围内有一个off by one错误,因此在修复该错误后,我得出以下结论:

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)
}

谢谢-这里有很多有用的信息-地图位特别有用@Caranthir,很高兴能帮上忙!请记住,我也是一个初学者,所以措辞和代码可能很笨拙。请随时询问是否有不清楚的地方,并查看我的答案的最新版本,以获得一个似乎有效的示例程序。对于这种特殊情况,您应该做的是
write!(&mut string,…)
如果
string
有容量,则将跳过分配。如果您正在做的不是附加到
string
,您可能需要编写类似
string=format!({}…,字符串,…)可能的重复也可能是您不知道需要答案的问题。
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.