TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Using unwrap() in Rust is okay

212 点作者 cp9将近 3 年前

16 条评论

dcsommer将近 3 年前
I totally agree with de-emphasizing the old &quot;recoverable&quot; vs. &quot;unrecoverable&quot; dichotomy (<a href="https:&#x2F;&#x2F;blog.burntsushi.net&#x2F;unwrap&#x2F;#what-about-recoverable-vs-unrecoverable-errors" rel="nofollow">https:&#x2F;&#x2F;blog.burntsushi.net&#x2F;unwrap&#x2F;#what-about-recoverable-v...</a>). Every time I&#x27;ve heard programmers (especially in the context of exceptions) try to define it, I&#x27;ve found it imprecise and open to debate.<p>When invariant violations or mistakes by programmers (aka bugs) are detected, the program should halt as it is in an inconsistent state and continuing could be very dangerous (think privacy&#x2F;security&#x2F;data corruption). Otherwise, don&#x27;t halt (handle it or have the caller handle it).
评论 #32387706 未加载
评论 #32389099 未加载
评论 #32390175 未加载
评论 #32387533 未加载
评论 #32387837 未加载
评论 #32387337 未加载
cedws将近 3 年前
The problem is that Rust developers don&#x27;t just use unwrap() when it <i>should</i> panic. I&#x27;ve seen plenty of &quot;production grade&quot; crates basically just unwrap because the author didn&#x27;t know how to handle it gracefully or just wanted to get the code compiling, then forgot about it.
评论 #32388332 未加载
评论 #32388076 未加载
评论 #32393203 未加载
评论 #32389773 未加载
评论 #32394299 未加载
评论 #32387528 未加载
评论 #32391235 未加载
评论 #32388166 未加载
ww520将近 3 年前
I generally just use expect(), assert!, or unreachable! rather than simply unwrap() to document the unexpected invalid state.
ComputerGuru将近 3 年前
One runtime panic I wish was a compile-time error in the rust standard library is the use of an incorrect memory order, eg Ordering::Release with AtomicBool::load().<p>It would have been fairly trivial to set up generic constraints specifying if a read, write, or read-write ordering semantic is expected and to fail to compile if it wasn’t met.
评论 #32387787 未加载
评论 #32388370 未加载
评论 #32394406 未加载
jeffrallen将近 3 年前
When you&#x27;ve gotten to the point of saying, &quot;well, it&#x27;s ok to panic in example code&quot; you&#x27;ve already lost the game. Novice programmers learn from example code, and novice programmers are an order of magnitude more common than experienced ones. A programming ecosystem that depends on 9 out of every 10 people being able to intuit that which the other 1 understands is not an ecosystem that&#x27;s going to produce good code.<p>Rust is a minefield of bear traps laid by experts, and I fear for the future of our industry if Go and Java programmers are required by some quirk of network effects or first mover advantage or whatever to starting programming (badly) in Rust.
评论 #32391293 未加载
richardwhiuk将近 3 年前
I think the `expect()` bad examples are something of a strawman.<p>The `.expect()` for regex for example would say what the regex is matching for.<p>I think it&#x27;d be desirable to have a `.unwrap_with_context(&quot;Context: {}&quot;)`, and the you&#x27;d get `Context: Inner Panic Info`.
评论 #32388246 未加载
评论 #32388264 未加载
评论 #32388267 未加载
schubart将近 3 年前
&gt; When checking preconditions, make sure the panic message relates to the documented precondition, perhaps by adding a custom message. For example,<p>&gt; `assert!(!xs.is_empty(), &quot;expected parameter &#x27;xs&#x27; to be non-empty&quot;)`.<p>This panics with<p>&gt; thread &#x27;main&#x27; panicked at &#x27;expected parameter &#x27;xs&#x27; to be non-empty&#x27;, src&#x2F;main.rs:79:5<p>Without the custom message it&#x27;s<p>&gt; thread &#x27;main&#x27; panicked at &#x27;assertion failed: !xs.is_empty()&#x27;, src&#x2F;main.rs:79:5<p>Given that panics should be for bugs, i.e. interpreted by developers, I&#x27;d say the second message is clear enough and a custom message just adds noise in the source code.
评论 #32392519 未加载
sitkack将近 3 年前
One can set the env var themselves in main(), many errors are transient, best to capture it the first time.<p><pre><code> &#x2F;&#x2F; use std::env; env::set_var(&quot;RUST_BACKTRACE&quot;, &quot;full&quot;);</code></pre>
评论 #32391077 未加载
koala_man将近 3 年前
tl;dr: Author convincingly argues that Rust `unwrap()` (Java `Optional.get`, Haskell `fromJust`) is fine when you either have checked that the call will not fail, or when you&#x27;re in a unit test or similar where a panic is a helpful result.<p>(And, conversely, that it&#x27;s not fine to use it to avoid doing real error handling)
评论 #32389360 未加载
评论 #32387771 未加载
dont_panic_将近 3 年前
my problem with panic is that it is like walking in a mine field, you don&#x27;t know which function will blow up at any given time, and it&#x27;s not checked by the compiler.<p>If there was some sort of signal to mark a function as panicking (&amp; vice versa), that would be nice.
评论 #32397383 未加载
cmrdporcupine将近 3 年前
The article has nuance. It&#x27;s good.<p>But the language has made it too easy to unwrap&#x2F;expect and panic.<p>This escape hatch should exist, for sure. But it ought to be more explicit, and more of a pain.<p>It is far too easy to reach for this tool.
评论 #32393414 未加载
renewiltord将近 3 年前
Very neat. Just discovered anyhow and the context stuff from this post.
berryton将近 3 年前
The Rust book has a small discussion about his in chapter 9.3 (<a href="https:&#x2F;&#x2F;doc.rust-lang.org&#x2F;book&#x2F;ch09-03-to-panic-or-not-to-panic.html" rel="nofollow">https:&#x2F;&#x2F;doc.rust-lang.org&#x2F;book&#x2F;ch09-03-to-panic-or-not-to-pa...</a>).<p>I think it is good to have some references (the blog post and the book) for when the horde comes after you.
yuan43将近 3 年前
The author notes that API simplicity might be a reason to avoid pushing invariants to compile time:<p>&gt; What do I mean by “API simplicity?” Well, this panic could be removed by moving this runtime invariant to a compile time invariant. Namely, the API could provide, for example, an AhoCorasickOverlapping type, and the overlapping search routines would be defined only on that type and not on AhoCorasick. Therefore, users of the crate could never call an overlapping search routine on an improperly configured automaton. The compiler simply wouldn’t allow it.<p>&gt; But this adds a lot of additional surface area to the API. And it does it in really pernicious ways. For example, an AhoCorasickOverlapping type would still want to have normal non-overlapping search routines, just like AhoCorasick does. It’s now reasonable to want to be able to write routines that accept any kind of Aho-Corasick automaton and run a non-overlapping search. In that case, either the aho-corasick crate or the programmer using the crate needs to define some kind of generic abstraction to enable that. Or, more likely, perhaps copy some code.<p>&gt; I thus made a judgment that having one type that can do everything—but might fail loudly for certain methods under certain configurations—would be best. The API design of aho-corasick isn’t going to result in subtle logic errors that silently produce incorrect results. If a mistake is made, then the caller is still going to get a panic with a clear message. At that point, the fix will be easy.<p>What I gather from this is that the author chose to define a type (call it A) with an attribute that when set in a certain way will cause certain functions to panic. This was preferred to the alternative (two types, A and B) with functions specific to each and where panic was not possible.<p>This kind of design decision comes up a lot, so understanding the reasoning here could be helpful in a lot of situations. Unfortunately, the passage is less than clear due to lack of source code inline and the highly-specific nature of the problem. An example with source code using more accessible algorithms might be an improvement here.<p>That said, I&#x27;m skeptical that the full range of approach was considered. I sometimes find that the presence of unwrap is a smell pointing to types that have not been fully fleshed out.<p>As an extreme case, consider a struct whose fields contained diverse data (numbers, colors, enumerated values), but which are all defined as strings. It will be very easy to put this struct into an inconsistent runtime state because nothing can be checked at compile time. The type itself is anemic. Replacing strings with more constrained types eliminates opportunities for panic - possibly all of them.<p>I get that the whole point is &quot;at what cost?&quot; All I&#x27;m saying is that the tradeoffs aren&#x27;t clear from the example in the passage.
评论 #32397584 未加载
nnoitra将近 3 年前
This blog post will age out in 6 months.
评论 #32391264 未加载
ArrayBoundCheck将近 3 年前
Does this mean using C inside of rust is ok? I&#x27;m pretty sure the original team kept hitting memory problems and it was in fact not ok. Browsers crash often enough that I don&#x27;t want unwrap making it worse
评论 #32387832 未加载