0

I am working on my first Rust project, a CLI application to find large files on a local filesystem. Rust has excellent documentation regarding match statements but I do not see how I can assign a value returned by the function passed to the match statement in a new variable:

pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let mut results_map: Option<Results>; match search(&config.root_path) { Err(e) => eprintln!("Error when calling run(): {:?}", e), Ok(results) => results_map = results), // how to properly assign value returned by function here? } Ok(()) } pub struct Results { result_map: HashMap<String, u64>, } pub fn search(path: &str) -> Result<Results, io::Error> { let root_path = Path::new(path); let mut results = Results { result_map: HashMap::<String, u64>::new()}; match visit_dirs(root_path, &mut results) { Err(e) => eprintln!("Error calling visit_dirs() from search(): {:?}", e), _ => (), } Ok(results) } 
1
  • 1
    You must pattern match the result. Currently you match it with _ (dont care). Since you care about the result you should match with an expression Ok(result) instead. As here Commented Dec 5, 2022 at 0:39

1 Answer 1

1

The functions you're calling in the match statements, search and visit_dirs return Result types. You have to use one of the arms of the match statement to cover the Ok (happy) case, next to where you're already covering the Err (error) case:

match search(&config.root_path) { Ok(results) => return results, Err(e) => eprintln!("Error when calling run(): {:?}", e), } 

Or you can assign the result of the match expression to a new variable:

let new_variable = match search(&config.root_path) { Ok(results) => results, // no return here Err(e) => { eprintln!("Error when calling run(): {:?}", e) // Either choose to panic (not recommended) // panic!("Bad times lie ahead") // Or propagate the error from your own Result return Err(e); }, } 

You may want to look into the ? operator to simplify this in the common case.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for such a well explained solution. I've used the ? operator in other functions that return the unit type, but I am not sure how to use it in the context of assigning whatever value is contained in Ok() to a new variable. Can you explain?
@JohnHarrington For instance if your function returned the same error type as the function you're calling (or a supertype of it), you could simply do let new_variable = search(&config.root_path)?; and it would handle the early return (though not the printing obviously) for you and there would be no need for a match arm.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.