简体   繁体   English

如何将 while 循环内的用户输入添加到 Rust 中的向量?

[英]How to add user input from inside a while loop to a vector in Rust?

I am making a program where the user enters words that get saved to a vector for future reference.我正在制作一个程序,用户可以在其中输入保存到向量中以供将来参考的单词。 Basically, I have a while loop that as long as the user doesn't desire to end the loop, will allow the user to keep entering words and have them inserted into a vector.基本上,我有一个 while 循环,只要用户不想结束循环,就会允许用户继续输入单词并将它们插入到向量中。 However, I keep getting error messages, relating to mutable and immutable or ownership issues.但是,我不断收到与可变和不可变或所有权问题相关的错误消息。

The following is my code.以下是我的代码。

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();
    }
}

Here is the error I got:这是我得到的错误:

error[E0382]: borrow of moved value: `WordInput`
  --> src/main.rs:23:31
   |
19 |     let mut WordInput = String::new();
   |         ------------- move occurs because `WordInput` has type `String`, which does not implement the `Copy` trait
...
23 |         io::stdin().read_line(&mut WordInput).expect("Failed");
   |                               ^^^^^^^^^^^^^^ value borrowed here after move
...
27 |         words.push(WordInput);
   |                    --------- value moved here, in previous iteration of loop

I have tried a lot of different solutions, like using &str, various usage of mutable and immutables, but nothing fixes the issue.我尝试了很多不同的解决方案,比如使用 &str,可变和不可变的各种用法,但没有解决问题。 Is there a fix to this issue, or should I try something else?这个问题有解决办法吗,还是我应该尝试其他方法?

A "borrow of moved value" error occurs when a variable's ownership is moved into a different scope, even though it is used later on in the same scope.当变量的所有权被移动到不同的范围时,即使稍后在同一范围内使用它,也会发生“移动值借用”错误。

To explain for this example, what happens is that on a hypothetical first iteration of the while loop:为了解释这个例子,会发生什么情况是在 while 循环的假设第一次迭代中:

  1. WordsInput is pushed into words which means that WordsInput can no longer refer to that string. WordsInput被推入words ,这意味着WordsInput不能再引用该字符串。 Therefore...所以...
  2. ...On a next iteration, WordsInput does not refer to anything, even though an attempt to access it is made here. ...在下一次迭代中, WordsInput不引用任何内容,即使在此处尝试访问它也是如此。

Rust's compiler detects that this occurs in your code and does not allow it to compile. Rust 的编译器检测到这发生在您的代码中,并且不允许它编译。

A way to solve this is to push WordsInput.clone() into words instead of WordsInput .解决这个问题的一种方法是将WordsInput.clone()推入words而不是WordsInput The clone method creates a new instance of a string which is moved into the words scope, while leaving WordsInput in its own scope. clone方法创建一个新的字符串实例,该实例被移入words范围,同时将WordsInput留在其自己的范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用While循环将用户键盘输入与字符串进行比较 - Comparing User Input From The Keyboard To A String Using A While Loop 如何在C编程中将用户输入与字符串进行while循环比较 - how to compare user input to a string for a while loop in c programming input.nextLine()在while循环内有一个字符串 - input.nextLine() with a string inside a while loop 无限while循环,.nextLine()用户输入 - infinite while loop, .nextLine() user input 使用While循环进行用户输入验证 - User input validation using While loop 如何在 rust 中返回字符串向量 - How to return a vector of strings in rust Do-while 或 while 循环将继续从用户那里获取输入,但在我用 c 语言输入字符串“exit”(不区分大小写)后将终止 - Do-while or while loop that will keep taking an input from user but will terminate after I input the string "exit" (case insensitive) in c language 在 Rust 中将字符串向量转换为 u32 向量时出现 InvalidDigit - InvalidDigit while converting vector of strings to vector of u32 in Rust 如何在用户输入的字符串中添加数字 - How to add digits within a string from user input 如何一次将来自用户输入的多个值存储到向量中(在 C++ 中)? - How do I store multiple values from user input into a vector at once (in c++)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM