我正在制作一个程序,在那里用户输入保存到矢量中的单词,以备将来参考.基本上,我有一个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 --&gt;src/main.rs:23:31 | 19|让mut WordInput=字符串::new(); |-因为WordInput的类型是String,没有实现Copy的特征 ... 23|io::stdin().read_line(&amp;mut WordInput).Expect("FAILED"); |^^搬家后在此借入的价值 ... 27|words.ush(WordInput); |-在循环的上一次迭代中,值移至此处

我try 了很多不同的解决方案,比如使用&amp;str,可变变量和不可变变量的各种用法,但都不能解决这个问题.这个问题有解决方法吗,或者我应该try 其他方法?

推荐答案

当变量的所有权被移到不同的作用域时,即使后来在同一作用域中使用了该变量,也会发生"borrow 移动值"错误.

为了解释本例,While循环的假设第一次迭代会发生以下情况:

  1. WordsInput被推入words,这意味着WordsInput不能再引用该字符串.因此...
  2. 在下一次迭代中,WordsInput不是指任何东西,即使在这里试图访问它.

Rust的编译器检测到您的代码中出现了这种情况,并且不允许对其进行编译.

解决这一问题的一种方法是将WordsInput.clone()推入words,而不是WordsInput.clone方法创建一个字符串的新实例,该实例被移到words作用域中,同时将WordsInput保留在它自己的作用域中.

Rust相关问答推荐

在actix—web中使用Redirect或NamedFile响应

如何创建引用构造函数拥有的变量的对象?

从Type::new()调用函数

什么时候和为什么S最好是按值或引用传递简单类型

使用Py03从Rust调用Python函数时的最佳返回类型

为什么';t std::cell::ref使用引用而不是非空?

如何正确重新排列代码以绕过铁 rust 借入判断器?

在Rust中,Box:ed struct 与普通 struct 在删除顺序上有区别吗?

Rust proc_macro 和 syn:解析空格

为什么这个闭包没有实现Fn?

Rust并发读写引起的死锁问题

rust 中不同类型的工厂函数

在每个循环迭代中删除borrow

切片不能被 `usize` 索引?

为什么具有 Vec 变体的枚举没有内存开销?

使用 serde_json 进一步处理字段

TcpStream::connect - 匹配武器具有不兼容的类型

Rust 为什么 (u32, u32) 的枚举变体的大小小于 (u64)?

如果返回类型是通用的,我可以返回 &str 输入的一部分吗?

为什么可以从不可变 struct 的字段中移动?