您可以使用 option< pathbuf> 并使用 stdin 当 none 时,所有内容都包含在方法中(是,您必须实现它自己):
option< pathbuf>
stdin
none
use std::io::BufReader; use clap; use std::io::BufRead; use std::path::PathBuf; // 3.1.6 #[derive(clap::Parser)] struct Reader { input: Option<PathBuf>, } impl Reader { fn reader(&self) -> Box<dyn BufRead> { self.input.as_ref() .map(|path| { Box::new(BufReader::new(std::fs::File::open(path).unwrap())) as Box<dyn BufRead> }) .unwrap_or_else(|| Box::new(BufReader::new(std::io::stdin())) as Box<dyn BufRead>) } }
You can use an Option<PathBuf> and use stdin when None, everything wrapped into a method (yes, you have to implement it yourself):
Option<PathBuf>
None
Playground
该解决方案:不使用动态调度,是详细的,使用 default_value_t ,需要夜间参见 #93965 (应该不需要每晚都需要,但对我来说更简单)
default_value_t
#93965
use clap; // 3.1.6 use std::fmt::{self, Display, Formatter}; use std::fs::File; use std::io::{self, stdin, BufRead, BufReader, Read, StdinLock}; use std::str::FromStr; enum Input { Stdin(StdinLock<'static>), File(BufReader<File>), } impl Display for Input { fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!(fmt, "Input") } } impl Default for Input { fn default() -> Self { Self::Stdin(stdin().lock()) } } impl FromStr for Input { type Err = io::Error; fn from_str(path: &str) -> Result<Self, <Self as FromStr>::Err> { File::open(path).map(BufReader::new).map(Input::File) } } impl BufRead for Input { fn fill_buf(&mut self) -> Result<&[u8], io::Error> { match self { Self::Stdin(stdin) => stdin.fill_buf(), Self::File(file) => file.fill_buf(), } } fn consume(&mut self, amt: usize) { match self { Self::Stdin(stdin) => stdin.consume(amt), Self::File(file) => file.consume(amt), } } } impl Read for Input { fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> { match self { Self::Stdin(stdin) => stdin.read(buf), Self::File(file) => file.read(buf), } } } #[derive(clap::Parser)] struct Reader { #[clap(default_value_t)] input: Input, }
This solution: Doesn't use dynamic dispatch, is verbose, use default_value_t, require nightly see #93965 (It should be possible to not require nightly but it's was simpler for me)
#93965
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
暂无简介
文章 0 评论 0
接受
发布评论
评论(2)
您可以使用
option&lt; pathbuf&gt;
并使用stdin
当none
时,所有内容都包含在方法中(是,您必须实现它自己):You can use an
Option<PathBuf>
and usestdin
whenNone
, everything wrapped into a method (yes, you have to implement it yourself):Playground
该解决方案:不使用动态调度,是详细的,使用
default_value_t
,需要夜间参见#93965
(应该不需要每晚都需要,但对我来说更简单)This solution: Doesn't use dynamic dispatch, is verbose, use
default_value_t
, require nightly see#93965
(It should be possible to not require nightly but it's was simpler for me)