我正在做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());
}
这也将失败,因为最后的迭代将添加一个空格。
如果我们在最后一次迭代中,我想我可以编写一个条件,但我正在努力使语法正确。此外,我觉得有一个更好的解决方案,所有这一切,我只是无法弄清楚语法。
如何使上面的断言在循环中通过条件传递,以便不在最后一次迭代中添加空格?
你可以使用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下正常。
如果你宁愿坚持公案的约束并使用for循环,你可以按照你的建议使用if
(弄清楚你是否最后使用enumerate
),或者pop
结束时的最后一个空格的字符串:
#[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());
}