13 easy Rust tips (code review)

  Рет қаралды 18,734

strager

strager

Күн бұрын

Write idiomatic Rust with these actionable tips and tricks. I reviewed a calculator (parser + interpreter) written in Rust and found a few ways to make it better and faster.
0:00 wrap(unwrap())
0:13 if {true} else {false}
0:19 String → str slice
0:34 if let ... && ...: github.com/rust-lang/rfcs/blo...
1:45 .copy() → 'static
2:06 HashSet[str] → bit set
3:03 compiler tests
4:00 how to split big functions
4:48 shorten error code
5:01 assert!
5:37 returning &mut
6:03 multi match
6:16 converting errors
7:20 code review final thoughts
Chat with me live for free code reviews, lessons, and career advice: / strager
stethoscope clipart PNG Designed By 颖 from Pngtree.com
Acid Trumpet music by Kevin MacLeod; incompetech.com/ CC-BY 3.0

Пікірлер: 38
@fennewald5230
@fennewald5230 2 жыл бұрын
For the bit options, seems like the perfect case for enumSet, which does all the fancy bit operations in a really easy-to-use way
@sacredindolent1765
@sacredindolent1765 Жыл бұрын
Nice video! My two cents: in tip #10, I'd use unreachable!() rather than assert!(), as a small way to document why I'm asserting. Also instead of assert!(2+2==4), you can do assert_eq!(2 + 2, 4), which will give a clearer error message if it fails.
@Gisleburt
@Gisleburt Жыл бұрын
Nice video. For ok_or though, I noticed the error takes a String which is created with format!. Using ok_or means you'd have to allocate that memory on the heap and create that string whether you need it or not. Here you'd get a small bump from ok_or_else as this takes a function that only runs if it's needed, saving you the allocation unless the function runs. Tbf though, clippy would point this out when you run it so less necessary to address in the code review.
@strager_
@strager_ Жыл бұрын
You're right. In Rust today, I think .ok_or() would force the allocation. I didn't think consider that. .ok_or_else() or match is the right thing to do if efficiency is important.
@Speykious
@Speykious Жыл бұрын
​@@strager_ Clippy even warns about using ok_or_else instead in case there's an allocation. Now there's also the `let ... else` syntax which is more readable and perfectly adapted for this use-case: let Some(token) = self.values.pop() else { return Err(...); };
@marcossidoruk8033
@marcossidoruk8033 11 ай бұрын
Instead of the unreadable if let && nonsense and instead of the nesting you could just invert the conditions and put them sequentially, like this: loop { if !condition1 { break; } if !condition2 { break; } if !condition3 { break; } DO SOMETHING HERE } That is a generally useful pattern that can reduce nesting significantly and makes all your conditions much more readable. It also works in basically any language.
@strager_
@strager_ 11 ай бұрын
Guard clauses are indeed a good idea! However, they won't work for destructuring (e.g. pulling out the character from self.peek()). They would work for the other conditions though.
@bigtymer4862
@bigtymer4862 2 жыл бұрын
Great video, and love your rust tips. I agree with everything you had to say. Would love to see more of these!
@strager_
@strager_ 2 жыл бұрын
What are you interested in specifically? Rust videos? Tip videos? Rust tip videos?
@0xedb
@0xedb 2 жыл бұрын
@@strager_ more Rust
@jaysistar2711
@jaysistar2711 2 жыл бұрын
Great video. It looks like many of these apply for C, C++, and Zig as well.
@leddoo
@leddoo Жыл бұрын
man, i wish the `if let &&` thing worked.. oh and about the bit ops: this seems to be a compiler, so the lower memory use could improve cache behavior.
@AdithyadevRajesh
@AdithyadevRajesh 4 ай бұрын
you could use is_some_and here instead of pattern matching, leading to `maybe_x.is_some_and(|x| x < 10)`
@hirisraharjo
@hirisraharjo 2 жыл бұрын
Great video man! Would love a bit more explanation about bit operation at minute ~2.40
@Codotaku
@Codotaku 6 ай бұрын
the assert isn't just mere documentation, but it also helps giving the compiler some context and guarantees so it potentially optimize further
@strager_
@strager_ 6 ай бұрын
This is a nice-to-have, but such optimizations never matter in my experience.
@v0xl
@v0xl Жыл бұрын
about the let-chains thing. You can use let-else there!
@superspartanman4480
@superspartanman4480 Жыл бұрын
These videos are extremely informative and well made, thank you!
@spicybaguette7706
@spicybaguette7706 Жыл бұрын
1:40 I think you can use while let Some(x @ ..10) = maybe_x
@strager_
@strager_ Жыл бұрын
Clever! Probably *too* clever...
@jeffg4686
@jeffg4686 2 жыл бұрын
just adding a note on the Copy one - for const, it doesn't matter as it just copies the value around at compile time (inlines the value) - though this is Rust, and I may be overlooking something ...
@strager_
@strager_ 2 жыл бұрын
The function copies the data to the stack in order to return Some(ADDITION_ASSIGNMENT_TOKEN) (~5 or 6 machine words). My suggestion is to instead copy a reference (1 machine word), which can be done more cheaply. The copy might disappear if the function is inlined, but I doubt a big function like this would be inlined.
@jeffg4686
@jeffg4686 2 жыл бұрын
@@strager_ - oh gotcha, makes sense
@alishergaliev7714
@alishergaliev7714 2 жыл бұрын
Can you please tell me the name of the font you are using?
@strager_
@strager_ 2 жыл бұрын
In my terminal/editor, I'm using Comic Code: tosche.net/fonts/comic-code
@MaxCoplan
@MaxCoplan 2 жыл бұрын
Thank you for the vid. These tips are easier than chicks after I tell them I program in Rust
@strager_
@strager_ 2 жыл бұрын
I use Rust, btw
@EndermanAPM
@EndermanAPM Жыл бұрын
I understand that you might not know an answer while streaming and just roll with it. What I'm not sure is why would you keep the tip if it's invalid. (talking about the if ... let)
@strager_
@strager_ Жыл бұрын
> why would you keep the tip if it's invalid. (talking about the if ... let) It might be valid in a future version of Rust: github.com/rust-lang/rfcs/blob/master/text/2497-if-let-chains.md The takeaway is that Rust evolves and that you should look to see if there's a nicer way to write your code. If someone really wants the feature, they can implement it in the Rust compiler! github.com/rust-lang/rust/issues/53667
@najidnadri792
@najidnadri792 2 жыл бұрын
My err handling: Let some_result = myfunc(); If let Err(e) = some_result { return Err(e) } let some_result = some_result.unwrap(); Is this a good way in handling error? because IMHO this is much cleaner than spamming match patterns
@optiphonic_
@optiphonic_ Жыл бұрын
Should just be able to go let some_result = myfunc()?;, and the Err will be automatically returned
@hamzadlm6625
@hamzadlm6625 Жыл бұрын
Blasingly fast!
@michelvandermeiren8661
@michelvandermeiren8661 Жыл бұрын
C++ was already too complex for me but RUST is completely out of my world, only aliens can code with RUST
@taladar3itch560
@taladar3itch560 Жыл бұрын
We need a Rust++.
@martiananomaly
@martiananomaly Жыл бұрын
Imo C is way harder than both Rust and C++. It's a completely different ball game with loads of segmentation faults and ease to make memory bugs.
@laxsjo.
@laxsjo. 10 ай бұрын
​@@martiananomalyI like to compare c and rust in this way. In c creating a program takes a long time, since writing the program is relatively quick, but you'll be debuging endless segfaults. Rust takes a long time because writing a program that the compiler accepts will take you a long time, but once it compiles, it will have virtually no memory bugs. You can definitely argue about which method is faster over all, and I personally prefer rusts way, but I'm not here to argue about that.
@martiananomaly
@martiananomaly 10 ай бұрын
@@laxsjo. yeah, having worked a fair share with both, Rust is definitely the better language.
@max_ishere
@max_ishere 2 жыл бұрын
There is a matches!() macro for if let
How to contribute to open source
14:15
strager
Рет қаралды 102 М.
8 deadly mistakes beginner Rust developers make
14:14
Let's Get Rusty
Рет қаралды 156 М.
Каха ограбил банк
01:00
К-Media
Рет қаралды 5 МЛН
Rust multi-threading code review
12:13
Tantan
Рет қаралды 195 М.
Big O myths busted! (Time complexity is complicated)
21:33
strager
Рет қаралды 131 М.
Tips for C++ newbies (compiler code review)
5:35
strager
Рет қаралды 10 М.
How I use C++: a line-by-line code review
1:40:40
strager
Рет қаралды 230 М.
Tonic makes gRPC in Rust stupidly simple
19:08
Dreams of Code
Рет қаралды 41 М.
Optimizing with "Bad Code"
17:11
Kaze Emanuar
Рет қаралды 194 М.
going fast is about doing less
19:41
leddoo
Рет қаралды 170 М.
Rust: When C Code Isn't Enough
8:26
CodeAhead
Рет қаралды 153 М.
Rust's lifetimes made easy
6:39
timClicks
Рет қаралды 9 М.
WWDC 2024 Recap: Is Apple Intelligence Legit?
18:23
Marques Brownlee
Рет қаралды 6 МЛН
i like you subscriber ♥️♥️ #trending #iphone #apple #iphonefold
0:14
AI от Apple - ОБЪЯСНЯЕМ
24:19
Droider
Рет қаралды 126 М.
ТОП-5 культовых телефонов‼️
1:00
Pedant.ru
Рет қаралды 18 М.