我在做Rust Koans 我陷入了一个问题:
#[test]
fn for_loops_two() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
let space: &str = " ";
let mut sentence: String = String::new();
for word in words.iter() {
// __
}
println!("{:?}", sentence);
assert!(sentence == "I love Rust".to_string());
}
我知道我需要连接字符串,但这会失败:
#[test]
fn for_loops_two() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
let mut sentence: String = String::new();
for word in words.iter() {
sentence.push_str(word);
}
println!("{:?}", sentence); // "ILoveRust"
assert!(sentence == "I love Rust".to_string());
}
我可以在每次迭代后添加一个空格:
#[test]
fn for_loops_two() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
let space: &str = " ";
let mut sentence: String = String::new();
for word in words.iter() {
sentence.push_str(word);
sentence.push_str(space);
}
println!("{:?}", sentence); // "I Love Rust "
assert!(sentence == "I love Rust".to_string());
}
这也将失败,因为最后的迭代将添加一个空格。
我想如果我们在上一次迭代中,我可以写一个条件语句,但是我在努力使语法正确。而且,我觉得所有这些都有更好的解决方案,我只是想不出语法。
如何使上面的断言在循环中带有条件,而不在上一次迭代中添加空间?
答案 0 :(得分:1)
有点晚了,但这里有一个只修改循环内块的解决方案:
#[test]
fn for_loops_two() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
let mut sentence: String = String::new();
for word in words.iter() {
if sentence != "".to_string() {
sentence.push(' ')
}
sentence.push_str(word)
}
println!("{:?}", sentence);
assert!(sentence == "I love Rust".to_string());
}
答案 1 :(得分:-1)
您可以使用slice::join
:
#[test]
fn for_loops_two() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
let sentence = words.join(" ");
assert!(sentence == "I love Rust".to_string());
}
关于链接的SliceConcatExt
特性的注释:在文档中被列为不稳定,但是方法是稳定的-在当前的稳定版Rust上,上述编译就很好。 / p>
如果您希望遵守koan的约束条件并使用for循环,则可以按照您的建议使用if
(使用{{3}来确定您是否最后}),或enumerate
字符串末尾的最后一个空格:
#[test]
fn for_loops_two_with_len_check() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
const SPACE: char = ' ';
let number_of_words = words.len();
let mut sentence = String::new();
for (i, word) in words.iter().enumerate() {
sentence.push_str(word);
if i < number_of_words-1 {
sentence.push(SPACE);
}
}
assert!(sentence == "I love Rust".to_string());
}
#[test]
fn for_loops_two_with_pop() {
let words: [&'static str; 3] = ["I", "love", "Rust"];
const SPACE: char = ' ';
let mut sentence = String::new();
for word in words.iter() {
sentence.push_str(word);
sentence.push(SPACE);
}
let _ = sentence.pop();
assert!(sentence == "I love Rust".to_string());
}