我是 Rust 新手,正在阅读官方书籍。我正在研究一个简单的 grep 示例,并希望创建一个exit可以在不同地方使用的函数。不幸的是,在闭包中使用此函数unwrap_or_else会导致编译错误。我不清楚为什么,因为当我直接在闭包中使用函数的内容时,它会起作用。
这是我的main.rs文件:
use std::env;
use std::fs;
use std::process;
use std::error::Error;
use std::fmt::Display;
struct Config{
query: String,
filename: String,
}
impl Config {
fn new(input: &[String]) -> Result<Config, &'static str> {
if input.len() < 3 {
return Err("Not enough arguments provided.");
}
let query = input[1].clone();
let filename = input[2].clone();
Ok(Config { query, filename })
}
}
fn run(cfg: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(&cfg.filename)?;
contents.find(&cfg.query).expect("Corrupted text …Run Code Online (Sandbox Code Playgroud)