Actually, it seems to only have eaten a single instance of <dyn Error>
. So this is probably what your code looks like
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub filename: String,
}
impl Config {
pub fn new(args: &[String]) -> Result<Config, &str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let filename = args[2].clone();
Ok(Config { query, filename })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.filename)?;
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast. productive."], search(query, contents));
}
}
(in the playground)
Any you’re getting both an (I guess expected) warning about contents
being unused, and (unrelatedly) a test failure:
warning: unused variable: `contents`
--> src/lib.rs:21:9
|
21 | let contents = fs::read_to_string(config.filename)?;
| ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_contents`
|
= note: `#[warn(unused_variables)]` on by default
running 1 test
test tests::one_result ... FAILED
failures:
---- tests::one_result stdout ----
thread 'tests::one_result' panicked at 'assertion failed: `(left == right)`
left: `["safe, fast. productive."]`,
right: `[" safe, fast, productive."]`', src/lib.rs:48:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::one_result
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
It gives you all the information needed. The difference is between
"safe, fast. productive."
and
" safe, fast, productive."
That’s one period vs. comma and some spaces from indentation. Both is easily fixed of course (playground after the fix).
To clarify, the warning about contents
being unused does also apply to the original source code. It is however only a warning, not an error. Also in general with Rust’s compiler it is almost always worth it to try and read the actual compiler output / error message in detail. If you use an IDE that doesn’t display the error messages in full (or you’re not sure how to make it show you the full error message) you can always still use the cargo
command, e.g. in this case cargo test
to get the output in your terminal if you’re otherwise unsure what’s going on.