嗨,我想能够读取一个文件,其中包含json行到一个rust应用程序像这样
$ cargo run < users.json
,然后作为迭代器读取这些行。到目前为止,我有这段代码,但我不希望文件硬编码,而是像上面的行一样管道到进程中。
use std::fs::File;
use std::io::{self, prelude::*, BufReader};
fn main() -> io::Result<()> {
let file = File::open("users.json")?;
let reader = BufReader::new(file);
for line in reader.lines() {
println!("{}", line);
}
Ok(())
}
我刚刚解决了这个问题
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
for line in stdin.lock().lines() {
println!("{}", line.unwrap());
}
}
cargo help run
:
NAME
cargo-run - Run the current package
SYNOPSIS
cargo run [options] [-- args]
DESCRIPTION
Run a binary or example of the local package.
All the arguments following the two dashes (--) are passed to the binary to run. If you're passing arguments to both Cargo and the binary, the ones after -- go to the binary, the ones before go to Cargo.
传递参数的语法是:
cargo run -- foo bar baz
你可以这样访问这些值:
let args: Vec<String> = env::args().collect();
一个完整的最小示例是:
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
dbg!(&args);
}
运行cargo run -- users.json
将导致:
$ cargo run -- users.json
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/sandbox users.json`
[src/main.rs:5] &args = [
"target/debug/sandbox",
"users.json",
]
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
for line in stdin.lock().lines() {
println!("{}", line.unwrap());
}
}