3 ms·
> when you do unwrap() you're saying the Result should NEVER fail Returning a Result by definition means the method can fail.
by Rohansi 11mo ago
> when you do unwrap() you're saying the Result should NEVER fail
Returning a Result by definition means the method can fail.
- Dylan16807 11mo ago> Returning a Result by definition means the method can fail. No more than returning an int by definition means the method can return -2.
- yoyohello13 11mo agoWhat? Results have a limited number of possible error states that are well defined.
- Dylan16807 11mo agoSome call points to a function that returns a Result will never return an Error. Some call points to a function that returns an int will never return -2. Sometimes you know things the type system does not know.
- Rohansi 11mo agoThe difference is functions which return Result have explicitly chosen to return a Result because they can fail. Sure, it might not fail in the current implementation and/or configuration, but that could change later and you might not know until it causes problems. The type system is there to help you - why ignore it?
- Dylan16807 11mo agoBecause it would be a huge hassle to go into that library and write an alternate version that doesn't return a Result. So you're stuck with the type system being wrong in some way. You can add error-handling code upfront but it will be dead code at that point in time, which is also not good.
- jamincan 11mo agoAs a hypothetical example, when making a regex, I call `Regex::new(r"/d+")` which returns a result because my regex could be malformed and it could miscompile. It is entirely reasonable to unwrap this, though, as I will find out pretty quickly that it works or fails once I test the program.
- bigstrat2003 11mo ago> No more than returning an int by definition means the method can return -2. What? Returning an int does in fact mean that the method can return -2. I have no idea what your argument is with this, because you seem to be disagreeing with the person while actually agreeing with them.
- Dylan16807 11mo ago> What? Returning an int does in fact mean that the method can return -2. What? No it doesn't. fn square(n: i32) -> i32 { n * n } This method cannot return -2. Though in this case it's more like knowing that the specific way you call the function in foo.rs will never get back a -2. fn bar(n: i32, allow_negative: bool) -> i32 { let new = n * 2; if allow_negative || new >= 0 { new } else { 0 } } bar(x, false)
- SchwKatze 11mo agoYeah, I think I expressed wrongly here. A more correct version would be: "when you do unwrap() you're saying that an error on this particular path shouldn't be recoverable and we should fail-safe."
- Buttons840 11mo agoDivision can fail, but I can write a program where I'm sure division will not fail.