如何在Rust的while循环中将用户输入添加至Vector?
问题修复方案
错误原因
报错核心是所有权转移:String类型未实现Copy trait,执行words.push(WordInput)时,WordInput的所有权会完全转移到Vec中,原变量变为无效状态。下一次循环调用io::stdin().read_line(&mut WordInput)时,试图借用已失去所有权的变量,因此触发错误。
修复方案
方案1:每次循环新建WordInput
将WordInput的声明移至while循环内部,每次迭代创建新的String,确保每次push的都是独立变量,不会影响下一次循环使用:
use std::io; fn CarryOn()->i8{ println!("Do you want to continue adding words to the glossary?"); println!("Press 1 for yes, enter any other number for no."); let mut s1 = String::new(); io::stdin().read_line(&mut s1).expect("Failed"); let n1:i8 = s1.trim().parse().expect("Not a valid Number"); return n1; } fn main(){ let mut words: Vec<String> = Vec::new(); println!("What's your name?"); let mut name = String::new(); io::stdin().read_line(&mut name).expect("Failed"); println!("Welcome {}",name); let mut LastWord = 1; words.push("Hello".to_string()); while LastWord == 1 { let mut WordInput = String::new(); // 移到循环内,每次新建变量 println!("Please type a word to add to the glossary"); io::stdin().read_line(&mut WordInput).expect("Failed"); WordInput.make_ascii_lowercase(); println!("{}",WordInput); words.push(WordInput); LastWord = CarryOn(); } }
方案2:使用take()方法复用变量
String::take()会拿走原字符串的所有内容,留下空的String,原变量仍保持有效,可在下一次循环中继续写入:
use std::io; fn CarryOn()->i8{ println!("Do you want to continue adding words to the glossary?"); println!("Press 1 for yes, enter any other number for no."); let mut s1 = String::new(); io::stdin().read_line(&mut s1).expect("Failed"); let n1:i8 = s1.trim().parse().expect("Not a valid Number"); return n1; } fn main(){ let mut words: Vec<String> = Vec::new(); println!("What's your name?"); let mut name = String::new(); io::stdin().read_line(&mut name).expect("Failed"); println!("Welcome {}",name); let mut LastWord = 1; let mut WordInput = String::new(); words.push("Hello".to_string()); while LastWord == 1 { println!("Please type a word to add to the glossary"); io::stdin().read_line(&mut WordInput).expect("Failed"); WordInput.make_ascii_lowercase(); println!("{}",WordInput); words.push(WordInput.take()); // 拿走内容,原变量留空可复用 LastWord = CarryOn(); } }
方案对比
- 方案1逻辑直观,适合新手理解,每次创建新变量的性能开销可忽略。
- 方案2复用变量,避免重复内存分配,性能略优,但需要理解
take()的所有权语义。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

