我试图从文件中读取值以创建结构,但遇到了一对奇怪的错误。我的代码的超级基本实现:
extern crate itertools;
use itertools::Itertools;
use std::io::{self, prelude::*, BufReader};
use std::fs::{self, File};
// The struct I will unpack into
struct BasicExample {
a: String,
b: String,
c: String,
d: String,
}
impl BasicExample {
pub fn new(a: String, b: String, c: String, d: String} -> Self {
BasicExample {
a, b, c, d
}
}
// I'm expecting that reading from the config file might fail, so
// I want to return a Result that can be unwrapped. Otherwise an Err
// will be returned with contained value being &'static str
pub fn from_config(filename: &str) -> io::Result<Self, &'static str> {
let file = File::open(filename).expect("Could not open file");
// read args into a Vec<String>, consuming file
let args: Vec<String> = read_config(file);
// I transfer ownership away from args here
let params: Option<(String, String, String, String)> = args.drain(0..4).tuples().next();
// Then I want to match and return, I could probably do if-let here
// but I don't have my hands around the base concept yet, so I'll
// leave that for later
match params {
Some((a, b, c, d)) => Ok(BasicExample::new(a, b, c, d)),
_ => Err("Could not read values into struct")
}
}
fn read_config(file: File) -> Vec<String> {
let buf = BufReader::new(file);
buf.lines()
.map(|l| l.expect("Could not parse line"))
.collect()
}
}
Running cargo check
为了确保我没有错过任何内容,我收到以下错误:
error[E0107]: wrong number of type arguments: expected 1, found 2
--> src/lib.rs:37:60
|
37 | pub fn from_config(filename: &str) -> io::Result<Self, &'static str> {
| ^^^^^^^^^^^^ unexpected type argument
error: aborting due to previous error
For more information about this error, try `rustc --explain E0107`.
看起来有点奇怪。io::Result
应该采取<T, E>
,我已经给了它E
,所以让我们删除该类型参数并看看会发生什么:
error[E0308]: mismatched types
--> src/lib.rs:54:22
|
54 | _ => Err("Could not read values into AzureAuthentication struct"),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::io::Error`, found reference
|
= note: expected type `std::io::Error`
found type `&'static str`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
出于某种原因,它真的不满意E
我提供的。我是一个完全的 Rust 初学者,所以也许我只是不确定我在看什么。我在这里做错了什么?这itertools
所有权技巧是从(ha)借来的这个精彩的答案 https://stackoverflow.com/a/43658017/7867968.
系统详细信息:
- macOS 10.13.6
- rustc 1.36.0 (a53f9df32 2019-07-03)
- 货物 1.36.0 (c4fcfb725 2019-05-15)