Q16. 哪个示例正确使用了 std::collections::HashMap 的 Entry API 来填充计数?
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
let text = "LinkedIn Learning";
for c in text.chars() {
// Complete this block
}
println!("{:?}", counts);
}
for c in text.chars() {
if let Some(count) = &mut counts.get(&c) {
counts.insert(c, *count + 1);
} else {
counts.insert(c, 1);
};
}
for c in text.chars() {
let count = counts.entry(c).or_insert(0);
*count += 1;
}
for c in text.chars() {
let count = counts.entry(c);
*count += 1;
}
for c in text.chars() {
counts.entry(c).or_insert(0).map(|x| x + 1);
}
参考
Q17. 在向“文件”(由 Vec<u8> 表示)写入时,哪个片段不会导致内存分配?
use std::
collections::HashMap;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut v = Vec::<u8>::new();
let a = "LinkedIn";
let b = 123;
let c = '🧀';
// replace this line
println!("{:?}", v);
Ok(())
}
write!(&mut v, "{}{}{}", a, b, c)?;
v.write(a)?;
v.write(b)?;
v.write(c)?;
v.write(a, b, c)?;
v.write_all(a.as_bytes())?;
v.write_all(&b.to_string().as_bytes())?;
- 在 rust 用户论坛中已回答
- 参考