pub fn lock(&self) -> StdinLock<'_>
Run Code Online (Sandbox Code Playgroud)
这在什么情况下有用?
文件指出,我的重点是:
进程的标准输入流的句柄。
每个句柄都是对此进程的输入数据的全局缓冲区的共享引用。可以使用句柄
lock来获得对BufRead方法的完全访问权限(例如,.lines())。否则,对该句柄的读取将相对于其他读取被锁定。
use std::io::{self, prelude::*};
fn main() {
let stdin = io::stdin();
dbg!(stdin.lines().count()); // fails!
let stdin = stdin.lock();
dbg!(stdin.lines().count());
}
Run Code Online (Sandbox Code Playgroud)
error[E0599]: no method named `lines` found for struct `std::io::Stdin` in the current scope
--> src/main.rs:6:16
|
6 | dbg!(stdin.lines().count());
| ^^^^^ method not found in `std::io::Stdin`
|
= note: the method `lines` exists but the following trait bounds were not satisfied:
`std::io::Stdin: std::io::BufRead`
which is required by `&mut std::io::Stdin: std::io::BufRead`
Run Code Online (Sandbox Code Playgroud)