You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:30:40