如何在不接收“未使用变量"的情况下获得用户输入?警告? [英] How can I get user input without receiving an "Unsed Variable" warning?

查看:45
本文介绍了如何在不接收“未使用变量"的情况下获得用户输入?警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Rust,并决定构建一个小程序,该程序可以接受用户的输入并进行打印,但是还希望对其进行一些数学上的练习.目前,这是我接受用户输入的方式:

I'm taking a look at Rust and decided to build a small program that takes a user's input and prints it, but also want to do some math stuff with it for practice. Currently, this is how I am taking user input:

let mut number = String::new();

let input = io::stdin().read_line(&mut number)
    .ok()
    .expect("Failed to read line");

println!("You entered {}", number);

但是,尽管我确实以这种方式获得了正确的输入,但Cargo还是给了我以下警告:

However, although I do get the correct input this way, Cargo gives me the following warning:

src/main.rs:10:9:10:14警告:未使用的变量: input ,默认情况下#[warn(unused_variables)]启用

src/main.rs:10:9: 10:14 warning: unused variable: input, #[warn(unused_variables)] on by default

src/main.rs:10让input = reader.read_line(& mut number)

src/main.rs:10 let input = reader.read_line(&mut number)

如果我只使用 input 变量,无论我输入什么数字,我都会得到一个"2".作为回报,当我打印号码时.

If I were to just use the input variable, no matter what number I enter I would get a "2" in return when I print the number.

如何避免该警告?是否有另一种方法可以在不创建2个变量绑定的情况下接受输入?

How can I avoid the warning? Is there another way for me to take input without creating 2 variable bindings?

推荐答案

您不能简单地将值写入变量.只要该值的类型未标记为 must_use ,您就可以忽略该值.

You can simply not write the value to a variable. As long as the type of the value is not marked must_use, you can ignore the value.

let mut number = String::new();

io::stdin().read_line(&mut number)
           .ok()
           .expect("Failed to read line");

println!("You entered {}", number);


[商业]

您可以将 text_io 板条箱用于

You can use the text_io crate for super short and readable input like

let i: i32 = read!()
let tup: (i32, String) = read!("{}, {}");

[/commercial]

这篇关于如何在不接收“未使用变量"的情况下获得用户输入?警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆