我正在尝试写cat
命令来学习 Rust,但我似乎无法将命令行参数转换为阅读器结构。
use std::{env, io};
use std::fs::File;
fn main() {
for arg in env::args().skip(1) {
let reader = match arg.as_str() {
"-" => io::stdin(),
path => File::open(&path).unwrap(),
};
}
}
Error:
error[E0308]: match arms have incompatible types
--> src/main.rs:6:22
|
6 | let reader = match arg.as_str() {
| ^ expected struct `std::io::Stdin`, found struct `std::fs::File`
|
= note: expected type `std::io::Stdin`
= note: found type `std::fs::File`
note: match arm with an incompatible type
--> src/main.rs:8:21
|
8 | path => File::open(&path).unwrap(),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
似乎不可能多态地匹配特征实现者(有关的) https://stackoverflow.com/questions/26126683/how-to-match-trait-implementors。我怎样才能使用File
or Stdin
作为读者?
问题是stdin()
返回类型的对象Stdio
and File::open(...).unwrap()
返回类型的对象File
。在 Rust 中,匹配的所有分支都必须返回相同类型的值。
在这种情况下,您可能想返回一个常见的Read
目的。很遗憾Read
是一个特征,所以你不能通过值传递它。最简单的替代方案是诉诸堆分配:
use std::{env, io};
use std::io::prelude::*;
use std::fs::File;
fn main() {
for arg in env::args().skip(1) {
let reader = match arg.as_str() {
"-" => Box::new(io::stdin()) as Box<Read>,
path => Box::new(File::open(&path).unwrap()) as Box<Read>,
};
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)