TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Using unwrap() in Rust is Okay (2022)

55 pointsby pierremenard4 days ago

12 comments

Zambyte2 days ago
The article pretty much says this as well, but a concise way I saw Andrew Kelley put it recently in the context of Zig (but it seems to apply well for any language that has errors-as-values + panics) is: &quot;Assertions for programmer mistakes; errors for user mistakes.&quot;[0]<p>One interesting difference between Zig and other languages with similar error stories (Rust, Go) is that panicking can be <i>handled</i> but not <i>recovered</i>. Panicking is always fatal in Zig. The nice thing about this is that you cannot use panics for exception-style control flow, which removes any temptation to use them for user errors.<p>[0] <a href="https:&#x2F;&#x2F;ziggit.dev&#x2F;t&#x2F;i-wrote-a-simple-sudoku-solver&#x2F;9924&#x2F;12?u=zambyte" rel="nofollow">https:&#x2F;&#x2F;ziggit.dev&#x2F;t&#x2F;i-wrote-a-simple-sudoku-solver&#x2F;9924&#x2F;12?...</a>
评论 #44051189 未加载
评论 #44050316 未加载
评论 #44056990 未加载
评论 #44050285 未加载
davidjfelix2 days ago
Unwrap is fine if used sparingly and as mentioned, to indicate a bug, but in practice it requires discipline and some wisdom to use properly - and by that I mean not just &quot;oh this function should be a `Result` but I&#x27;ll add that later (never).<p>I think relying on discipline alone in a team is usually a recipe for disaster or at the very least resentment while the most disciplined must continually educate and correct the least disciplined or perhaps least skilled. We have a clippy `deny` rule preventing panics, excepts, and unwraps, even though it&#x27;s something we know to sometimes be acceptable. We don&#x27;t warn because warnings are ignored. We don&#x27;t allow because that makes it too easy to use. We don&#x27;t use `forbid`, a `deny` that can&#x27;t be overridden, because there are still places it could be helpful. What this means is that the least disciplined are pushed to correct a mistake by using `Result` and create meaningful error handling. In cases where that does not work, extra effort can be used to add an inline clippy allow instruction. We strongly question all inline clippy overrides to try to avoid our discipline collapsing into accepting always using `unwrap` &amp; `allow` at review time to ensure nothing slips by mistakenly. I will concede that reviews themselves are potentially a dangerous &quot;discipline trap&quot; as well, but it&#x27;s the secondary line of defense for this specific mistake.
wiktor-k2 days ago
&gt; That section briefly described that, broadly speaking, using unwrap() is okay if it’s in test&#x2F;example code or when panicking indicates a bug.<p>I&#x27;ve come to the conclusion that even in tests unwraps look ugly. Especially in doc tests which serve as examples the code is better off using regular &quot;?&quot; that one would see in other parts of code. (that is: don&#x27;t treat test code as a &quot;worse&quot; kind of code)<p>In Signstar we&#x27;re using testresult which still panics under the hood (which is OK for tests) <a href="https:&#x2F;&#x2F;gitlab.archlinux.org&#x2F;archlinux&#x2F;signstar&#x2F;-&#x2F;blob&#x2F;main&#x2F;nethsm&#x2F;src&#x2F;openpgp.rs#L167" rel="nofollow">https:&#x2F;&#x2F;gitlab.archlinux.org&#x2F;archlinux&#x2F;signstar&#x2F;-&#x2F;blob&#x2F;main&#x2F;...</a> but the rendered example looks a lot better: <a href="https:&#x2F;&#x2F;docs.rs&#x2F;nethsm&#x2F;latest&#x2F;nethsm&#x2F;enum.OpenPgpVersion.html#impl-FromStr-for-OpenPgpVersion" rel="nofollow">https:&#x2F;&#x2F;docs.rs&#x2F;nethsm&#x2F;latest&#x2F;nethsm&#x2F;enum.OpenPgpVersion.htm...</a><p>Note that I&#x27;m currently maintaining that crate but the design is described at <a href="https:&#x2F;&#x2F;www.bluxte.net&#x2F;musings&#x2F;2023&#x2F;01&#x2F;08&#x2F;improving_failure_messages_rust_tests&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.bluxte.net&#x2F;musings&#x2F;2023&#x2F;01&#x2F;08&#x2F;improving_failure_...</a>
评论 #44050048 未加载
评论 #44051081 未加载
评论 #44050293 未加载
voidUpdate2 days ago
While I don&#x27;t fully understand rust (not that I&#x27;ve really attempted to program in it much), I do really like the Result&lt;T, E&gt; convention. Before I knew about it, I used a similar construct in a couple of places in my C# code, but I think I&#x27;ll make my own version of it and try to use it more often. I don&#x27;t think C# has a builtin version anyway, I know it has a builtin that does the same as Option&lt;T&gt; with its nullable types, like int?, which can either be an int or null
评论 #44050456 未加载
评论 #44051111 未加载
the__alchemist2 days ago
Great article by a rust legend. Two points:<p><pre><code> - The let-else syntax (Relatively new), anecdotally, removes many of my cases for unwrap. (But this may not apply to how others use it) - Unwrap&#x27;s fine if it makes the code easier-to-read and you know it won&#x27;t panic for a reason the compiler doesn&#x27;t know about.</code></pre>
axegon_2 days ago
I saw that article in 2023 and I have mixed feelings. In general there are cases where you want a program to crash and it&#x27;s a preferable option as opposed to a never-ending chain of handling. For that purpose, unwrap is actually perfect. It is also great for examples, documentation, so that people can see what to expect and how a certain block should behave.<p>But there&#x27;s the other case(which I&#x27;ve also suffered from). It is tempting to do the fast thing when you are on a tight schedule. One such instance was when we had to deliver something which was arguably undeliverable within the deadline we had. There were two services which were communicating over gRPC, and to make matters worse, not tonic but some custom implementation. But those worked surprisingly well against all odds. But there was a third service where we had to use a regular, plain ol&#x27; boring http requests. &quot;I&#x27;m returning you the ID as a string inside the response, just cast it to a 32 bit integer and you&#x27;re good to go&quot; they said. &quot;Fair&quot;, I thought: response_id::&lt;i32&gt;().unwrap(), compile and deploy. Needless to say, the ID was not a 32 bit integer. Point is, if you control the entire ecosystem you are working on, unwrap, although undesirable in many cases, is fine. Anything else - handle the errors.
评论 #44051510 未加载
johnisgood2 days ago
I do not think a code full of unwrap() (which I have seen often) is a nice thing to look at.
评论 #44051415 未加载
vbezhenar2 days ago
The general issue, as I see it:<p>One function is too general and handles all inputs. Some inputs are wrong and code returns error. Some languages forces you to handle that error.<p>Another code snippet uses that function with very specific inputs which must not cause errors, but was forced to handle error, because of language rules. This error handling is essentially useless.<p>I saw this issue with Java. There&#x27;s constructor `new URI(String) throws URISyntaxException`. URISyntaxException is checked exception which must be handled at invocation site or propagated to the caller. But you might need to write code like `var uri = new URI(&quot;<a href="https:&#x2F;&#x2F;example.com&#x2F;" rel="nofollow">https:&#x2F;&#x2F;example.com&#x2F;</a>&quot;)` and any error handling code will only be to please the compiler, essentially wasted work. Java solved it using `public static URI create(String str)` which does not throw checked exceptions and you&#x27;re supposed to choose either constructor or factory method, depending in the circumstances.<p>Using Rust analogy, may be it would be useful for Java to write something like `var uri = unchecked new URI(&quot;<a href="https:&#x2F;&#x2F;example.com&#x2F;&quot;);" rel="nofollow">https:&#x2F;&#x2F;example.com&#x2F;&quot;);</a>`, so with minimal syntax overhead you would signal that checked exceptions are not supposed to occur here (and if they did occur, then some unchecked UnexpectedCheckedException would throw here). It&#x27;s actually possible to implement method `static T unchecked(CheckedSupplier&lt;T, E&gt; supplier)`, though syntax would be ugly: `var uri = unchecked(() -&gt; new URI(&quot;<a href="https:&#x2F;&#x2F;example.com&#x2F;" rel="nofollow">https:&#x2F;&#x2F;example.com&#x2F;</a>&quot;))`.<p>I think that this is general issue for programming languages. There&#x27;s only one way to validate input parameters and report error. But whether those input parameters are trusted or not - only the caller knows. So nothing wrong about using `unwrap()` to signify the fact, that caller already made sure that error does not happen. The only important nuance is that error must not be swallowed if it happened.
评论 #44050914 未加载
评论 #44051292 未加载
gwbas1c2 days ago
My biggest beef with &quot;unwrap&quot; is that it doesn&#x27;t contain an error message. Because I generally follow the mantra that panics are for unrecoverable errors, (typically bugs,) some kind of error message is critical in debugging the situation. (Because no program should fail with &quot;mystery error&quot;.)<p>I went back to <a href="https:&#x2F;&#x2F;doc.rust-lang.org&#x2F;core&#x2F;option&#x2F;enum.Option.html" rel="nofollow">https:&#x2F;&#x2F;doc.rust-lang.org&#x2F;core&#x2F;option&#x2F;enum.Option.html</a> and I can&#x27;t seem to find an alternative to &quot;unwrap&quot; that includes an error message. I vaguely remember finding an alternative to unwrap with an error message, but because I don&#x27;t use Rust on a daily basis, I can&#x27;t seem to remember how I did it.
评论 #44051364 未加载
评论 #44051361 未加载
perrygeo2 days ago
unwrap() is fine for experimental and WIP code. But it&#x27;s a code smell for production. I usually do a git grep for unwrap and go one of two ways:<p>1. convert to an expect() - even if a panic is fine, you at least owe the future reader an explanation.<p>2. Use &quot;proper&quot; result handling, usually let Some, .ok_or, or a match.<p>Unwrap is a nice ergonomic cheat code to get the program compiled and leave a little TODO for yourself. You just need the discipline to circle back and clean them up, just like any debugging tool.
Filligree2 days ago
Just don’t put unwrap in library code, please. Not if it can possibly happen, bearing in mind that you can make mistakes.<p>I like my background threads to be infallible. If they panic, then chances are nothing will notice and the rest of the program will solely seize up.<p>I might have agreed with more of this article if panics actually crashed the program, but in multithreaded Rust that’s rarely the case.
评论 #44051564 未加载
评论 #44050218 未加载
m00dy2 days ago
I only use unwrap in tests
评论 #44051136 未加载