【发布时间】:2020-05-23 05:31:31
【问题描述】:
我有两个三个不同版本的函数,它们模仿 python 中的 input 函数。
use std::io::{self, BufRead, BufReader, Write};
// Adapted from https://docs.rs/python-input/0.8.0/src/python_input/lib.rs.html#13-23
fn input_1(prompt: &str) -> io::Result<String> {
print!("{}", prompt);
io::stdout().flush()?;
let mut buffer = String::new();
io::stdin().read_line(&mut buffer)?;
Ok(buffer.trim_end().to_string())
}
// https://www.reddit.com/r/rust/comments/6qn3y0/store_user_inputs_in_rust/
fn input_2(prompt: &str) -> io::Result<String> {
print!("{}", prompt);
io::stdout().flush()?;
BufReader::new(io::stdin())
.lines()
.next()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Cannot read stdin"))
.and_then(|inner| inner)
}
// tranzystorek user on Discord (edited for future reference)
fn input_3(prompt: &str) -> io::Result<String> {
print!("{}", prompt);
std::io::stdout().flush()?;
BufReader::new(std::io::stdin().lock())
.lines()
.take(1)
.collect()
}
fn main() {
let name = input_1("What's your name? ").unwrap();
println!("Hello, {}!", name);
let name = input_2("What's your name? ").unwrap();
println!("Hello, {}!", name);
let name = input_3("What's your name? ").unwrap();
println!("Hello, {}!", name);
}
但它们似乎是非常不同的方法,我不知道使用其中一种方法是否有任何优势。根据我的阅读,拥有像 python 的 input 这样的函数并不像看起来那么简单,这就是标准库中没有的原因。
使用上面编写的任何版本可能会遇到什么问题?还有另一种更惯用的方式来编写这个input 函数吗? (2018年版)
另外,在这里:How can I read a single line from stdin? 一些答案使用lock() 方法,但我不明白它的目的。
我正在学习来自 python 的 Rust。
【问题讨论】:
标签: rust