pub fn stdout() -> Stdout展开描述
构造一个到当前进程标准输出流的新句柄。
The returned handle allows writing to standard out from the within the Tokio 运行时。
对 stdout 的并发写入必须谨慎执行:
只有此 AsyncWrite 上的单个写入才保证是完整的。
尤其是要注意,使用 write_all 进行的写入
不能保证作为单次写入发生,
因此多个线程使用
write_all 写入数据可能会导致输出交错。
请注意,与 std::io::stdout 不同,
每次调用此 stdout()
都会产生一个新的 writer,因此,例如,
此程序不会 flush stdout:
tokio::io::stdout().write_all(b"aa").await?;
tokio::io::stdout().flush().await?;§示例
use tokio::io::{self, AsyncWriteExt};
#[tokio::main]
async fn main() -> io::Result<()> {
let mut stdout = io::stdout();
stdout.write_all(b"Hello world!").await?;
Ok(())
}以下是在循环中使用 stdio 的示例。
use tokio::io::{self, AsyncWriteExt};
#[tokio::main]
async fn main() {
let messages = vec!["hello", " world\n"];
// When you use `stdio` in a loop, it is recommended to create
// a single `stdio` instance outside the loop and call a write
// operation against that instance on each loop.
//
// Repeatedly creating `stdout` instances inside the loop and
// writing to that handle could result in mangled output since
// each write operation is handled by a different blocking thread.
let mut stdout = io::stdout();
for message in &messages {
stdout.write_all(message.as_bytes()).await.unwrap();
stdout.flush().await.unwrap();
}
}