error handling - How to convert FromStrRadixErr to ParseIntError? -
i'm trying build generic wrapper around std::<t>::from_str_radix. according documentation, from_str_radix returns result<t, parseinterror>.
fn foo<t: num_traits::num>() -> result<t, std::num::parseinterror> { t::from_str_radix("4242", 10) } won't compile:
error: mismatched types: expected
core::result::result<t, core::num::parseinterror>, foundcore::result::result<t, <t num_traits::num>::fromstrradixerr>
on other hand, this
fn main() { let x: result<u8, std::num::parseinterror> = foo(); println!("{:?}", x); } fn foo<t: num_traits::num>() -> result<t, <t num_traits::num>::fromstrradixerr> { t::from_str_radix("4242", 10) } compiles fine , prints expected result
err(parseinterror { kind: overflow })
to mind, both same situation, i'm wrong. can explain me difference , possibly show me solution?
how convert
fromstrradixerrparseinterror?
it's not possible. errors, io::error, allow create instance causing error, can create error wraps error. if parseinterror had such functionality, create parseinterror caused fromstrradixerr error, parseinterror not.
can explain me difference?
this code:
fn foo<t: num_traits::num>() -> result<t, std::num::parseinterror> { t::from_str_radix("4242", 10) } does not compile because returned type of t::from_str_radix result<t, fromstrradixerr> not result<t, parseinterror>. changing return type (as did) result<t, fromstrradixerr>, solves problem.
this code:
fn main() { let x: result<u8, std::num::parseinterror> = foo(); println!("{:?}", x); } fn foo<t: num_traits::num>() -> result<t, <t num_traits::num>::fromstrradixerr> { t::from_str_radix("4242", 10) } compiles fine because num trait implementation u8 defines fromstrradixerr = parseinterror.
if change u8 f32:
let x: result<f32, std::num::parseinterror> = foo(); it fails compile. reason num implementation f32 defines fromstrradixerr = parsefloaterror , parsefloaterror not parseinterror.
and possibly show me solution?
you said trying build generic wrapper around std::<t>::from_str_radix, examples use t::from_str_radix t: num, trying write wrapper around num::from_str_radix.
one option use num , fromstrradixerr directly instead of creating wrapper, in end, num wrapper.
maybe want restrict wrapper primitive integers , use parseinterror. in case, can add restriction fromstrradixerr = parseinterror:
fn foo<t>() -> result<t, std::num::parseinterror> t: num_traits::num<fromstrradixerr = std::num::parseinterror>, { t::from_str_radix("4242", 10) }
Comments
Post a Comment