gpt4 book ai didi

rust - 关于值(value)的rustc误报从未读过?

转载 作者:行者123 更新时间:2023-12-03 11:41:10 26 4
gpt4 key购买 nike

跟随this article关于在Rust中编写shell。编译器会输出有关从未读取变量的警告。

use std::io::stdin;
use std::io::stdout;
use std::io::Write;
use std::process::Command;
use std::path::Path;

fn main(){
let mut input = String::new();

loop {
print!("> ");
stdout().flush().unwrap();
// input = String::from(""); // **<===== HERE**
stdin().read_line(&mut input).unwrap();
let mut parts = input.trim().split_whitespace();
let command = parts.next().unwrap();
let args = parts;
match command {
"cd" => {
let new_dir = args.peekable().peek().map_or("/", |x| *x);
let root = Path::new(new_dir);
if let Err(e) = std::env::set_current_dir(&root) {
eprintln!("{}", e);
}
},
"exit" => return,
command => {
let child = Command::new(command)
.args(args)
.spawn();
// gracefully handle malformed user input
match child {
Ok(mut child) => { child.wait().unwrap(); },
Err(e) => eprintln!("{}", e),
};
}
}
}
}
但是,注释掉这一行会导致程序错误:这是注释前后的行为:
usn@DESKTOP:~/bqy/rust/p2$ cargo run
warning: value assigned to `input` is never read
--> src/main.rs:8:10
|
8 | let mut input = String::new();
| ^^^^^
|
= note: `#[warn(unused_assignments)]` on by default
= help: maybe it is overwritten before being read?

Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/p2`
> ls
Cargo.lock Cargo.toml src target
> ls
Cargo.lock Cargo.toml src target
> exit
usn@DESKTOP:~/bqy/rust/p2$ vi src/main.rs
usn@DESKTOP:~/bqy/rust/p2$ cargo run
Compiling p2 v0.1.0 (/mnt/d/MMM/projects/bqy/rust/p2)
Finished dev [unoptimized + debuginfo] target(s) in 1.13s
Running `target/debug/p2`
> ls
Cargo.lock Cargo.toml src target
> ls
ls: cannot access 'ls': No such file or directory
> exit
ls: cannot access 'ls': No such file or directory
ls: cannot access 'exit': No such file or directory
> ^C
usn@DESKTOP:~/bqy/rust/p2$ vi src/main.rs
有害行为的简单说明是未重置命令行。那么,为什么编译器会提示呢?
感谢您的阅读。

最佳答案

如果没有清除缓冲区的行,它的内容将从一个迭代被重用到另一个迭代。这就是为什么您的程序不能没有的原因

input = String::from("");
但这会给您一个警告,因为您在声明 input时给了它一个值:
let mut input = String::new();
// ^^^^^^^^^^^^^^^^
并且不使用此值,因为从字面意义上来说, input的第一个用法是覆盖它。所以只是不要给它一个值:
let mut input;
在Rust中,这是绝对安全的,并且编译器不会让您在初始化之前不小心使用 input

另外,如果您的目标是重用缓冲区以节省内存,则应使用
input.clear();
因为 input = String::from("");使用新的缓冲区创建了一个全新的字符串,并将另一个丢弃。

关于rust - 关于值(value)的rustc误报从未读过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63055859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com