Basic Error Handling question: generic error type in return

I want to parse the second command line argument, parse it and return it as a Result<f32, Error> type. As you can see, the error type itself is not known in compile time. How can I write this function?

use std::error::Error;  
fn parse_income() -> Result<f32, Box<dyn Error>> {  
    Ok(std::env::args().nth(1)?.parse::<f32>()?) 
 }  

This code obviously won't compile primarily because nth() returns and option type. But I want to throw a NoneError in that case. Hence the compiler says:

expected type std::result::Result<_, std::boxed::Box<(dyn std::error::Error + 'static)>>
found type std::result::Result<_, std::num::ParseFloatError>

This concerns me because the Box<dyn Error> is not acting like a generic error type.

NoneError isn't an "error", because mixing of returning Result with Option was controversial. If you convert Option to Result, then it works:

Ok(std::env::args().nth(1).ok_or("missing arg")?.parse::<f32>()?) 
1 Like

ok_or()

Thanks for that, I've changed the function but the second problem persists.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c457e40be5a323831e6c910498499b32

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6343a972d93e56a32c553d65284c5a5f

You don't need to call into(), because ? does that already:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6f182876cff92f465c3dfef660fb7377

1 Like