gpt4 book ai didi

rust - 强制 io::stdio 和 BufReader 之间的 BufRead 特性兼容性

转载 作者:行者123 更新时间:2023-11-29 07:58:14 28 4
gpt4 key购买 nike

我正在尝试对一个 io::stdio 实例和一个包装文件的 BufReader 进行类型双关,这样我就可以在假定缓冲输入源的情况下编写代码。我已经尝试了几种尝试将 io::stdio() 转换为 BufRead 类型的变体,但都失败了,并出现了以下一种或多种变体:

error: mismatched types:
expected `std::io::stdio::StdinLock<'_>`,
found `std::io::buffered::BufReader<std::fs::File>`
(expected struct `std::io::stdio::StdinLock`,
found struct `std::io::buffered::BufReader`) [E0308]
csv_to_json.rs:26 reader = BufReader::new(file.unwrap());

代码如下:

use std::io;
use std::io::BufReader;
use std::io::prelude::*;
use std::env;
use std::process::exit;
use std::fs::File;

fn usage() {
println!("Usage: cat input.csv | csv_to_json");
}

fn main() {
let stdin = io::stdin();
let mut reader = stdin.lock(); // Assignment. (1)
let args: Vec<String> = env::args().collect();

if args.len() > 1 {
usage();
exit(1);
} else if args.len() == 1 {
let file = File::open(args[0].clone());
if !file.is_ok() {
usage();
exit(1);
}
reader = BufReader::new(file.unwrap()); // Reassignment. This is the line that fails.
}

// Rest of the code works with reader assuming a buffered input source.
}

我尝试过的事情:

let mut reader : BufRead = io::stdin();  // Fails.
let mut reader : BufReader<Read> = io::stdin(); // Fails.
let mut reader : BufReader<_> = io::stdin(); // Fails
let mut reader : BufRead = io::stdin().lock(); // Fails later.
let mut reader = BufReader::new(io::stdin()); // Fails with type mismatch.
let mut reader = BufReader::new(io::stdin().lock()); // Fails with type mismatch.

我什至尝试将该代码提取到它自己的函数中,但返回类型签名失败并出现类似的错误情况。我如何创建一个“阅​​读器”变量,它是 stdio 上的 BufferedReaderFile 上的 BufferedReader 而无需到处都面临类型错误?

最佳答案

您的代码可以重写,因此无需重新分配 reader 变量(请参阅@Vladimir Matveev answer)。

如果你真的需要它,那么 reader 变量必须是 trait object :

let mut bufread;//must be defined before reader to avoid lifetime issues 
let stdin = io::stdin();
let mut reader = &mut stdin.lock() as &mut BufRead; // Assignment. (1)

//...

bufread = BufReader::new(file.unwrap());//store BufReader value
reader = &mut bufread;// reassign BufRead reference

特征对象的盒装形式允许避免额外的变量bufread:

let stdin = io::stdin();
let mut reader = Box::new(stdin.lock()) as Box<BufRead>;

//...

reader = Box::new(BufReader::new(file.unwrap()));

关于rust - 强制 io::stdio 和 BufReader 之间的 BufRead 特性兼容性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36106280/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com