如何在 Rust 中的同一行打印 STDOUT 和获取 STDIN?

How do I print STDOUT and get STDIN on the same line in Rust?

println!()print!() 允许您分别打印带和不带尾随换行符的字符串和变量。此外,stdin() 函数提供了从 STDIN (stdin().read_line(&mut string)) 读取一行用户输入的函数。

可以安全地假设,如果连续使用 print 宏和 read_line 函数,您应该能够在同一行上写入输出和获取输入。但是,当发生这种情况时,这些段将以相反的顺序执行(首先读取 STDIN,然后打印语句)。

这是我要完成的示例:

use std::io;

fn main() {
    let mut input = String::new();
    print!("Enter a string >> ");
    io::stdin().read_line(&mut input).expect("Error reading from STDIN");
}

所需的输出将是(STDIN 表示要求用户输入的点,实际上并未打印):

Enter a string >> STDIN

实际输出为:

STDIN
Enter a string >> 

另一方面,println 宏不会颠倒顺序,尽管仍然存在尾随换行符的问题:

Enter a string >> 
STDIN

在 Python (3.x) 中,这可以用一行完成,因为 input 函数允许在 STDIN 提示符之前使用字符串参数:variable = input("Output string")

在 Rust 文档中找不到允许类似于 Python 示例的解决方案后,我将任务分为 print 宏和 read_line 函数。

stdout 在换行时刷新。由于您的 print! 语句不包含也不以换行符结尾,因此它不会被刷新。您需要使用 std::io::stdout().flush()

手动完成

例如

use std::io::{self, Write};

fn main() {
    let mut input = String::new();
    print!("Enter a string >> ");
    let _ = io::stdout().flush();
    io::stdin().read_line(&mut input).expect("Error reading from STDIN");
}

you should be able to write output and get input on the same line.

stdinstdout中没有"same line"的概念。只是有不同的流,如果你想执行终端操作,你应该使用处理终端的东西,比如 console.

In Python (3.x), this can be accomplished with a single line, because the input function allows for a string argument that precedes the STDIN prompt: variable = input("Output string")

好了,给你:

use dialoguer::Input;

let name = Input::new().with_prompt("Your name").interact()?;
println!("Name: {}", name);