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.

Rust concepts I wish I learned earlier

379 pointsby rckover 2 years ago

25 comments

anderskaseorgover 2 years ago
&gt; <i>With the code above, Rust does not know whether we want to clone Arc or the actual inner value, so the code above will fail.</i><p>This is incorrect. The code works fine as written; Rust will let you write .clone() and it will clone the Arc (without cloning the inner value). More generally, methods on a wrapper type are searched before methods found via auto-deref. It’s often considered better style to write Arc::clone(…), but that’s for human readability, not the compiler. There’s a Clippy lint for it (<a href="https:&#x2F;&#x2F;rust-lang.github.io&#x2F;rust-clippy&#x2F;master&#x2F;#clone_on_ref_ptr" rel="nofollow">https:&#x2F;&#x2F;rust-lang.github.io&#x2F;rust-clippy&#x2F;master&#x2F;#clone_on_ref...</a>) but it’s turned off by default.
评论 #34430966 未加载
kris-sover 2 years ago
The author mentions the following:<p><pre><code> fn add(x: Option&lt;i32&gt;, y: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; { if x.is_none() || y.is_none() { return None; } return Some(x.unwrap() + y.unwrap()); } The above looks kind of clunky because of the none checks it needs to perform, and it also sucks that we have to extract values out of both options and construct a new option out of that. However, we can much better than this thanks to Option’s special properties! Here’s what we could do fn add(x: Option&lt;i32&gt;, y: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; { x.zip(y).map(|(a, b)| a+b) } </code></pre> Do folks really prefer the latter example? The first one is so clear to me and the second looks inscrutable.
评论 #34429129 未加载
评论 #34429184 未加载
评论 #34430439 未加载
评论 #34429117 未加载
评论 #34434638 未加载
评论 #34435255 未加载
评论 #34429071 未加载
评论 #34429048 未加载
评论 #34445597 未加载
评论 #34429067 未加载
评论 #34429084 未加载
评论 #34431118 未加载
评论 #34429103 未加载
评论 #34432352 未加载
评论 #34429022 未加载
评论 #34429134 未加载
perrygeoover 2 years ago
Nice article, but I&#x27;m not sure I like using the Deref trait just to make code &quot;cleaner&quot; - it does the opposite IMO, making it harder to understand what&#x27;s going on.<p>Deref is convenient for builtin &quot;container&quot; types where the only thing you&#x27;ll ever do is access the singular value inside it. But sprinkling it everywhere can get confusing (&quot;why are we assigning a &amp;str to a struct here?&quot;)
评论 #34429996 未加载
woodruffwover 2 years ago
Nice list!<p>This is a nitpick on my part, but this part on PhantomData:<p>&gt; Tells the compiler that Foo owns T, despite only having a raw pointer to it. This is helpful for applications that need to deal with raw pointers and use unsafe Rust.<p>...isn&#x27;t <i>quite</i> right: `_marker: marker::PhantomData&lt;&amp;&#x27;a T&gt;,` doesn&#x27;t tell the compiler that `Foo` owns `T`, but that instances of `Foo` can&#x27;t outlive its `bar` member. `bar` is in turn borrowed, since a pointer is &quot;just&quot; an unchecked reference.<p>You can see this in the playground[1]: `foo1` and `foo2` have the same borrowed `bar` member, as evidenced by the address being identical (and the borrow checker being happy).<p>Edit: What I&#x27;ve written above isn&#x27;t completely correct either, since the `PhantomData` member doesn&#x27;t bind any particular member, only a lifetime.<p>[1]: <a href="https:&#x2F;&#x2F;play.rust-lang.org&#x2F;?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=65fb09c6ab9736761e244531b736b304" rel="nofollow">https:&#x2F;&#x2F;play.rust-lang.org&#x2F;?version=stable&amp;mode=debug&amp;editio...</a>
评论 #34429046 未加载
geeweeover 2 years ago
Having worked with Rust for a little while (about a year) none of this stuff is particularly esoteric. However it is a great list of things that are good to know, but you don&#x27;t necessarily need all that often (or learn from the official rust book)
评论 #34428939 未加载
friedman23over 2 years ago
I&#x27;ll share an architectural pattern from Rust that is pretty ubiquitous but not really mentioned in the official books.<p>Skip the whole weak rc nonsense and jump directly to using an allocator (like slotmap) when dealing with cyclic data structures. Wrap the allocator in a a struct to allow for easy access and all the difficulty from rust cyclic datastructures disappears.
ihnortonover 2 years ago
<p><pre><code> Really annoyed by the borrow checker? Use immutable data structures ... This is especially helpful when you need to write pure code similar to that seen in Haskell, OCaml, or other languages. </code></pre> Are there any tutorials or books which take an immutable-first approach like this? Building familiarity with a functional subset of the language, before introducing borrowing and mutability, might reduce some of the learning curve.<p>I suspect Rust does not implement as many FP-oriented optimizations as GHC, so this approach might hit performance dropoffs earlier. But it should still be more than fast enough for learning&#x2F;toy datasets.
评论 #34432269 未加载
评论 #34432450 未加载
评论 #34434818 未加载
puffoflogicover 2 years ago
Author has confused the drop functions. `Drop::drop` and `mem::drop` have nothing to do with each other.
评论 #34428980 未加载
kris-novaover 2 years ago
Great read — the author should feel proud. This made my morning.
linhnsover 2 years ago
This is somewhat off-topic but it&#x27;s nice to see someone using Zola for their own blog, awesome SSG built on Rust!
ElderKorihorover 2 years ago
&gt; Use impl types as arguments rather than generic constraints when you can<p>Eep. No. At least, not in anything public. Universal impl trait arguments can&#x27;t be turbofished, so you&#x27;re placing an unnecessary constraint on your caller.
评论 #34435944 未加载
评论 #34437101 未加载
cassepipeover 2 years ago
One thing I wish Rust and C++ had and that I have only seen in Carbon is pass-by-reference by default + an explicit syntax to pass by copy + for rust, some syntax to mark that we are passing a mutable&#x2F;exclusive reference.
评论 #34436114 未加载
jasonjmcgheeover 2 years ago
Small note- at least one of the links on mobile does not respect the text column width of the page, so the actual page width is wider than the text and horizontally scrollable.
atemerevover 2 years ago
Yes, most of my code deals with graph-like data structures. It is _really_ hard to understand how to write this in Rust. Just doesn&#x27;t fit in my head.
lesuoracover 2 years ago
Well not in the article but I saw somebody doing a guard clause that I started to copy.<p>i.e.<p>```<p>let min_id = if let Some(id) = foo()? { id } else { return; }<p>...<p>let bar = if let Some(bar) = baz()? { bar } else { return; }<p>..<p>&#x2F;&#x2F; vs<p>if let Some(id) = foo()? {<p>...<p>if let Some(bar) = baz()? {<p>..<p>}}<p>```<p>It&#x27;s nice to also do `if let (Some(x), Some(y)) = ...` but sometimes you need the result of `x` to do a few things before you can get `y` (or maybe don&#x27;t went to evaluate `y` depending on `x`).<p>---<p>I like the `where` syntax more than the example formatting.<p>```<p>fn x&lt;T&gt;(t: T) where T: Foo {}<p>```
评论 #34428888 未加载
endorphineover 2 years ago
&gt; There are two kinds of references in Rust, a shared reference (also known as a borrow)<p>Is that really what they&#x27;re called? It seems confusing to me: if it&#x27;s shared (i.e. many people use it at the same time) how can it also be borrowed (i.e. one person has it)?
评论 #34431324 未加载
ww520over 2 years ago
This is a fantastic list. I&#x27;ve certainly learned something new.<p>The comments here are unnecessary negative. People seem to be upset on things that don&#x27;t look familiar. Don&#x27;t let the negative comments get to you. Keep up the good work.
评论 #34492807 未加载
avinasshover 2 years ago
In the traits example<p>&gt; which tells the compiler “I just want something that implements Meow”.<p>The ‘trait Meower’ also implies same, right? If so, why can’t we use that
评论 #34437200 未加载
wizzwizz4over 2 years ago
&gt; <i>Normally, Rust would complain,</i><p>Not in the example given. There&#x27;s nothing wrong with creating an Rc&lt;T&gt; loop; the borrow checker doesn&#x27;t come into the picture.<p>&gt; <i>That is, you could mutate the data within an Rc as long as the data is cheap to copy. You can achieve this by wrapping your data within a Rc&lt;Cell&lt;T&gt;&gt;.</i><p>T: Copy is only a bound on the .get() method. You can do this even if the data is expensive to copy, so long as you always swap in a valid representation of T. (I sometimes write Cell&lt;Option&lt;T&gt;&gt;, where it makes sense to replace with a None value.)<p>&gt; <i>Embrace unsafe as long as you can prove the soundness of your API,</i><p>In other words: avoid unsafe except as a last-ditch resort.<p>&gt; <i>&amp;impl Meower</i><p>Should be impl Meower, if you want the same behaviour as the explicit-generic version.<p>&gt; <i>Many tutorials immediately jump to iterating over vectors using the into_iter method</i><p>Out of interest, what tutorials? I&#x27;ve never read one that does that!<p>&gt; <i>Instead, there are two other useful methods on iterators</i><p>Methods on many iterables in std. Not on iterators (nor iterables in general).<p>&gt; <i>You can wrap the following types with PhantomData and use them in your structs as a way to tell the compiler that your struct is neither Send nor Sync.</i><p>… You&#x27;re doing it wrong. €30 says your unsafe code is unsound.<p>&gt; <i>Embrace the monadic nature of Option and Result types</i><p>Er, maybe? But try boring ol&#x27; pattern-matching first. It&#x27;s usually clearer, outside examples like these ones (specially-chosen to make the helper methods shine). I&#x27;d go for if let, in this example – though if the function really just returns None in the failure case, go with the ? operator.<p>&gt; <i>For example, writing a custom linked list, or writing structs that use channels, would typically need to implement a custom version of Drop.</i><p>No, you don&#x27;t typically need to. Rust provides an automatic implementation that <i>probably</i> does what you need already. Custom drop implementations are mainly useful for unsafe code.<p>&gt; <i>Really annoyed by the borrow checker? Use immutable data structures</i><p>No. <i>No.</i> Haskell has all sorts of optimisations to make &quot;immutable everything&quot; work, and Rust&#x27;s &quot;do what I say&quot; nature means none of those can be applied by the compiler. If you want to program this way, pick a better language.<p>&gt; <i>Instead, you can define a blanket trait that can make your code a more DRY.</i><p>There are no blanket <i>traits</i>. There are blanket trait <i>implementations</i>, and you&#x27;ve missed that line from your example.<p>All in all, this is a good article. There are some good tips in there, but I wouldn&#x27;t recommend it to a beginner. I <i>would</i> recommend the author revisit it in a few months, and make some improvements: a tutorial <i>designed</i> when you&#x27;re green, but with the <i>experience</i> from your older self, can be a really useful thing.
评论 #34430695 未加载
评论 #34430471 未加载
1980phipsiover 2 years ago
The one about exclusive references is good.
lakomenover 2 years ago
God almighty, that language is sl fugly to look at
评论 #34434600 未加载
joshfeeover 2 years ago
&gt; there is a lot of excellent Rust content catering to beginners and advanced programmers alike. However, so many of them focus on the explaining the core mechanics of the language and the concept of ownership rather than architecting applications.<p>The author then goes on to write an article largely covering the mechanics of the language rather than architecting applications.
评论 #34429981 未加载
评论 #34433847 未加载
antmanover 2 years ago
I read this 3-4 times and realized why people stick to python though
评论 #34434816 未加载
评论 #34431551 未加载
评论 #34430948 未加载
评论 #34431691 未加载
评论 #34430867 未加载
评论 #34430599 未加载
评论 #34432132 未加载
评论 #34433562 未加载
评论 #34430604 未加载
评论 #34433684 未加载
评论 #34434815 未加载
评论 #34434628 未加载
评论 #34433838 未加载
cormacrelfover 2 years ago
“Fed up with the borrow checker? Try writing your own immutable linked list.” Yeah, that’ll help!
评论 #34428972 未加载
badrequestover 2 years ago
I love how Rust has so many footguns that you need to read a dozen blogs from no less than a month ago to avoid utter confusion.
评论 #34430583 未加载
评论 #34430728 未加载
评论 #34430505 未加载
评论 #34433292 未加载