我正在制作一个程序,在那里用户输入保存到矢量中的单词,以备将来参考.基本上,我有一个While循环,只要用户不想结束循环,它就允许用户继续输入单词并将它们插入到一个向量中.然而,我不断收到错误消息,与可变和不可变或所有权问题有关.
以下是我的代码.
use std::io;
fn CarryOn()->i8{ // function where it asks the user if he or she wants to stop input or not
println!("Do you want to continue ending 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()); // backup, just in case the user doesn't add a word.
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); //line of error; without, program runs fine, but program is useless
LastWord = CarryOn();
}
}
下面是我收到的错误:
错误[E0382]:borrow 移动值:WordInput
-->;src/main.rs:23:31
|
19|让mut WordInput=字符串::new();
|-因为WordInput
的类型是String
,没有实现Copy
的特征
...
23|io::stdin().read_line(&;mut WordInput).Expect("FAILED");
|^^搬家后在此借入的价值
...
27|words.ush(WordInput);
|-在循环的上一次迭代中,值移至此处
我try 了很多不同的解决方案,比如使用&;str,可变变量和不可变变量的各种用法,但都不能解决这个问题.这个问题有解决方法吗,或者我应该try 其他方法?