我正在学习Rust,但遇到了一些困难。
我想给用户提供将输出写入标准输出或提供的文件名的选项。
我从这里找到了使用
但是它输出以下错误:
但是我不明白问题出在哪里,因为
谢谢!
我想给用户提供将输出写入标准输出或提供的文件名的选项。
我从这里找到了使用
extra::getopts
的示例代码:here。在do_work
函数中,我尝试做到这一点:use std::io::stdio::stdout;
use std::io::buffered::BufferedWriter;
fn do_work( input: &str, out: Option<~str> ) {
println!( "Input: {}", input );
println!( "Output: {}", match out {
Some(x) => x,
None => ~"Using stdout"
} );
let out_writer = BufferedWriter::new( match out {
// I know that unwrap is frowned upon,
// but for now I don't want to deal with the Option.
Some(x) => File::create( &Path::new( x ) ).unwrap(),
None => stdout()
} );
out_writer.write( bytes!( "Test output\n" ) );
}
但是它输出以下错误:
test.rs:25:43: 28:6 error: match arms have incompatible types: expected `std::io::fs::File` but found `std::io::stdio::StdWriter` (expected struct std::io::fs::File but found struct std::io::stdio::StdWriter)
test.rs:25 let out_writer = BufferedWriter::new( match out {
test.rs:26 Some(x) => File::create( &Path::new( x ) ).unwrap(),
test.rs:27 None => stdout()
test.rs:28 } );
test.rs:25:22: 25:41 error: failed to find an implementation of trait std::io::Writer for [type error]
test.rs:25 let out_writer = BufferedWriter::new( match out {
^~~~~~~~~~~~~~~~~~~
但是我不明白问题出在哪里,因为
File
和StdWriter
都实现了Writer
特质。有人能解释一下我错在哪了吗?谢谢!
let out_writer: Box<Write> = ... Box::new(io::stdout()),
(不需要as ...
)在1.16版本中也可以工作。我不知道哪种更符合惯用法。 - mkjeldsen