Daily Rust Profile Banner
Daily Rust Profile
Daily Rust

@rustoftheday

Followers
1,527
Following
681
Media
100
Statuses
323

Daily tips & tricks for Rust 🦀 programming. Following back all accounts with 🦀 or 🐪 in their profile.

Joined November 2023
Don't wanna be here? Send us removal request.
Explore trending content on Musk Viewer
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 64: #TIL about NonZero numeric types, where you can guarantee at compile time that values will not be zero. It is also a true zero-cost #abstraction since if you define e.g., Option<NonZeroU8>, the "0" value will map to "None". Very nifty! Here's an example:
Tweet media one
4
15
126
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 74: The .zip() function for iterators in Rust allows transforming two vecs into a single vec of tuples. However, the syntax is not as convenient as #Python 's version. But this issue can be nicely addressed using #generics :
Tweet media one
7
6
101
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 70: This arcane syntactic feature in #match statements was suggested to me by a #follower : var_name @ match_value => ... allows you to #capture the value of match_value to use in the match block. This code example should make clear what is going on:
Tweet media one
6
9
98
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 56: Expanding on yesterday's #macros topic, today I explored the 10 #matchers plus the "ident" matcher, which I missed in the last post . Check out this grid showcasing #examples for each:
Tweet media one
2
10
98
@rustoftheday
Daily Rust
8 months
@gf_256 Isn't this valid (although not modern) C++ already?
1
0
95
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 48. One example where Rust really shines is handling #threads and reading their return values. This seems much easier to do than in many other languages. Here is a simple example of processing the results of two threads:
Tweet media one
1
8
93
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 82: When working with #paths , consider using std::path::PathBuf. This will help with path composition and manipulation and ensure that the output conforms to the #OS path representation:
Tweet media one
2
6
82
@rustoftheday
Daily Rust
8 months
@_injuly @gf_256 OK, very meta-level 😆
1
0
82
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 66: std::time::Instant can be used as a simple way of measuring the execution time of a block of code.
Tweet media one
1
5
76
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 73: The include_str!() and include_bytes!() macros make it possible to include a file as a string or a byte array at #compile #time . This avoids long and messy multiline string literals. The compiler even checks if the file is present, and prints an error if not.
Tweet media one
3
8
77
@rustoftheday
Daily Rust
5 months
🦀 #Rust #tip 86: #Enums also support a #default implementation. How do you specify which variant is the default? Use #[derive(Default) and specify a #[default] attribute:
Tweet media one
0
6
75
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 80: I needed to write a function where I can flexibly define the size of the output array (at compile time). It turns out that #const #generics are very helpful for this. "Const Generics" allow us to parametrize #types via constants, hence the name.
Tweet media one
4
7
72
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 27: Did you know that Rust supports #destructuring of most common data types? Here's an example for structs:
Tweet media one
4
13
69
@rustoftheday
Daily Rust
9 months
@DorianDevelops Also weird naming schemes: - S3 == "Storage/Bucket" - EC2 == "Compute" - Route 53 == "DNS" -LightSail == "Simple Compute" -Lamba == "Cloud Functions" etc..
8
4
66
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 75: Types marked with the Send marker #trait indicate that they are safe to move between threads. Rust use this to ensure #thread #safety at compile time. While the compiler automagically implements Send for many standard types, we put our trust in the developer
Tweet media one
3
7
58
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 79: &Option<T> or Option<&T> as function input parameter? Option<&T> seems to be the preferred way, since it offers more flexible conversions, and uses pointer niche optimization.
Tweet media one
1
7
58
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 60: When you #derive the Debug #trait , on a struct you get two formatters for println! - {:?} default debug formatter - {:#?} "pretty print" debug formatter What is the visual difference between the output? Let's find out:
Tweet media one
Tweet media two
4
9
59
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 63: When I started Rust programming I was surprised to never see any #raw #pointers in examples. Always Box<>, Arc<>, etc. Turns out that they do exist, but rarely used in idiomatic Rust. Looking deeper, here's a side-by-side comparison of C and Rust raw pointers:
Tweet media one
3
11
59
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 68: Today I found out that it is possible to define #constants in #Traits , and also redefine the values in specific impls of the trait. Still pondering the pros and cons. How would you leverage this feature? Share your thoughts!
Tweet media one
3
4
54
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 58: The Rust type system allows us to define "marker types", which can be structs with just a name, to encode #metadata about a specific #type . Here's an example of using marker structs for a Document struct that can be in "Draft" or "Published" state:
Tweet media one
5
3
47
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 69: If you find yourself in a situation where you have a #nested #option , e.g., Option<Option<T>>, you can use .flatten() to remove one level of nesting:
0
3
42
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 55. Took a deep dive into the world of declarative #macros in Rust. First step is to understand the basic syntax...This is certainly hard to describe as a post, so I made a (hopefully informative) image with the basics:
Tweet media one
0
9
43
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 52. Fn, FnMut, FnOnce. What are they? These are special #traits used to pass #closures as function arguments. - Fn: closure that doesn't modify environment - FnMut: can modify the env. - FnOnce: run once and consume env. Here's an example showing FnMut in action:
Tweet media one
1
7
42
@rustoftheday
Daily Rust
7 months
🦀 #Rust #Sunday #crate 13: nalgebra is Rust's equivalent to C++ Eigen or Python's NumPy -- a very comfortable library for #vectors and #matrices (and more).
0
2
37
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 67: Unit Structs and Tuple Structs are useful but lesser-known constructs in of the Rust type system. - Unit Structs can represent a concept at the type level. Also handy to implement a trait sans data. - Tuple Structs: similar to tuples but can implement fns
Tweet media one
1
4
38
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 84: The select! #macro from the Futures crate is intriguing. Like a #match statement for futures, it allows precise control over #async results. The downside is that set-up is a bit clunky.
Tweet media one
0
4
38
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 61: I got asked about #smart #pointers the other day. Here's a basic rundown on the Rc<T> smart pointer:
Tweet media one
0
1
36
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 72: Rust's #numeric types are cool! You can call common math functions directly on numeric values using dot notation. For instance, you can calculate the sine of 32.0 just by calling 32.0.sin(). This feature enhances #code readability and reduces the need for
1
4
35
@rustoftheday
Daily Rust
7 months
🦀 #Rust #Sunday #crate 14: Egui is a great way to quickly and easily build #UI applications in Rust.
1
6
31
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 62: This is a great article on #error handling in Rust and how to apply the #anyhow crate:
1
3
30
@rustoftheday
Daily Rust
7 months
986 #followers of Daily Rust 🦀. Let's get it to 1000!
2
2
28
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 76: Quick intro to running a #debugger on your Rust code: ➡️ build with debug symbols: cargo build ➡️ start lldb or rust-lldb (prettier output) with your program: lldb target/debug/your_app_name ➡️ set breakpoint at a specific line: breakpoint set --file
1
4
27
@rustoftheday
Daily Rust
7 months
1000 followers! Thank you for your interest and support 🚀🎉
Tweet media one
2
2
27
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 83: Are out parameters #idiomatic in Rust? I would say mostly not:
0
4
26
@rustoftheday
Daily Rust
8 months
@ThePrimeagen I’m increasingly getting the feeling that Rust is a high level language perceived as being a low level language. Using Rust effectively requires understanding of lots of high level concepts. C requires understanding of the machine itself.
2
0
26
@rustoftheday
Daily Rust
8 months
@Nexuist Give this person a quantum computer already!
0
0
25
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 71: Rust has #C -compatible #union types. They are inherently #unsafe since the union members share the same memory. The best use case I can think of is interop with C/C++, and perhaps binary data protocols, unioning byte arrays with other types.
Tweet media one
0
4
24
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 37: #Tuple #Structs are useful for wrapping values with extra metadata that can be verified by Rust's #type #system . A cool use for tuple structs is modeling a measurement unit - no more mixing up feet and meters:
Tweet media one
1
4
24
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 85: I explored how #attribute #macros , i.e., #[some_attribute], work. The process is OK but requires quite a bit of support crates, notably: - quote: for generating Rust code that expands into the output Rust TokenStream. - syn: for parsing and reasoning about
Tweet media one
0
2
22
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 50. If you are debugging your #iterator and just want to test just a subset of the data, you can use myvec.iter().take(N) to operate only on the first N items. Alternatively, you can also slice the input: &myvec[0..N].iter()
1
3
22
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 51. Struggling with map() on a list of #optionals in #iterators ? filter_map() elegantly handles this by ignoring None values and only processing Some() values:
Tweet media one
1
0
22
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 78: Here's a great overview of how to call an external #process from your Rust #code , and process the outputs.
0
3
19
@rustoftheday
Daily Rust
7 months
Rust Rust (luckily)
@mjovanc
Marcus Cvjeticanin
7 months
Language at work: Java Language I enjoy: Rust What about you?
51
0
110
4
2
19
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 30: #Iterators can be extended via the chain() function. Rust also gracefully handles chaining of #optionals that may or may not have a value:
Tweet media one
1
3
20
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 54. When working in #async Rust, and need to perform two (unrelated) tasks, you can dispatch them in parallel using the join! macro from the futures #crate . This can be more #efficient than calling .await on them sequentially:
Tweet media one
0
0
18
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 38: 30s guide to crafting a Rust #Module : Create your module structure: my_module/ ├── mod. rs ├── component_1.rs └── component_2.rs In mod. rs add: mod component_1; mod component_2; 🌟 Tip: Use pub for #public access.
1
3
19
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 57: There are three main locations where you can implement Rust #tests : - as part of your documentation (doctest) - under your code in an embedded test (#[cfg(test)]) - in an external test folder 👉 Run tests by executing "cargo test"
1
0
19
@rustoftheday
Daily Rust
7 months
@fredine I have observed that devs learning Rust without a knowledge of C/C++ have a hard time wrapping their heads around the concepts of "borrow", "pointer", "heap" and "stack". Having background in those languages is not necessary but useful to accelerate the initial learning curve.
4
2
18
@rustoftheday
Daily Rust
9 months
🦀 #Rust #Sunday #crate 4: SQLx is a #database client for Rust that supports #PostgreSQL , #MySQL , #SQLite . SQLx checks the (schema-)correctness of #SQL statements in your Rust code at #compile time, by connecting to the database. Crazy stuff!
1
1
18
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 59: I ran into a few cases where I tried to implement an #extension #trait and the compiler wouldn't let me. It turns out that there are two rules to observe: 1) If the trait is defined in your crate, you can implement extensions for any type, even those in other
0
2
16
@rustoftheday
Daily Rust
8 months
@cleancodestudio I don’t get all the complaints that Rust compiles slowly. Compared to other languages is subjectively quite speedy. E.g, in C++ even small projects with a main file and very few includes can take >20s to compile, larger ones 10s of minutes.
2
0
16
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 34: Option<T>.map() is a great way to #convert #options from one type to another. Map handles the presence of #None values transparently. Check out this example where we convert from Option<u32> to Option<String>:
Tweet media one
0
2
14
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 45: Here's an interesting factoid for those of you who wish to ultra- #optimize your #code : std::hint allows you to tell the compiler that a given boolean expression is likely to be true, therefore enabling optimized branch prediction:
Tweet media one
1
2
14
@rustoftheday
Daily Rust
8 months
🦀 #Rust #Sunday #crate 10: I started work on a #3D #visualization project and looked into a few 3D #graphics crates last week: - Bevy Engine (): fully-featured, but you will get locked into their entity-component model and way of doing things. - Fyrox
0
2
13
@rustoftheday
Daily Rust
8 months
🦀 #Rust #Sunday #crate 9: I'd like to highlight the indicatif crate today. It provides a #progressbar library for the command line, similar to #Python 's TQDM, but on steroids. Check it out! (image from )
0
4
12
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 40: There are actually two flavors of #macros in Rust. #Declarative and (the more advanced) #procedural macros. Here's an example of a declarative macro_rules! macro that generates a println function:
Tweet media one
0
0
14
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 44: Rust #web #server with static file serving and a default route to index.html in actix_web. Almost as simple as #JavaScript ?
Tweet media one
0
3
15
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 32: #iterators have some cool convenience functions. One of them is it.all(), which checks a given condition for all elements of the iterator. This allows us to rewrite ugly #for #loop based code in elegant, #idiomatic ways:
Tweet media one
1
3
14
@rustoftheday
Daily Rust
8 months
Exciting milestone reached! 🎉 We've surpassed 500 followers in our #daily #Rust journey. Huge thanks to the amazing Rustacean community 🦀 for your support and engagement. Stay tuned for more top-notch content! #RustLang #CodingCommunity
0
0
12
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 41: Similar to #Golang 's #channels , std::sync::mpsc provides a safe mechanism to read/write data between threads in Rust:
Tweet media one
0
1
12
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 49. Simple #parallelization of a for loop using the Rayon crate by adding an import and using the .par_iter() parallel #iterator provided by Rayon. The code counts elements >0. Expected speedup is ~X where X is the nr. of CPU cores you have:
Tweet media one
1
0
12
@rustoftheday
Daily Rust
8 months
🦀 #Rust #Sunday #crate 11: Looking for a library that can handle #image IO similar to Python's #PIL ? The Image crate has you covered!
1
0
10
@rustoftheday
Daily Rust
9 months
Wow, this marks one month of @rustoftheday , bringing you bite-sized morsels of #Rust -related knowledge, #daily . We started this account as we believe that Rust #developers need to know a lot of small facts to be effective. Thank you for all the likes and follows! ❤️🦀
0
1
11
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 46: Have you ever been confused by the PartialEq and Eq #traits ? Here's a quick rundown: PartialEq: Implemented via eq method (not to be mixed up with Eq!), it enables equality (==) checks. If items aren't comparable, eq returns false. Eq: A "marker trait"
0
1
9
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 81: Remaining on the topic of #compile #time operations, concat!() is a nifty macro that concatenates string literals (i.e., &str) at compile time. Possible use cases are composing static resource paths or status messages.
0
3
10
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 47. Some strategies to avoid the #dreaded clone(): - use borrows (&) when passing to a read-only function - use Rc<T> or Arc<T> to share ownership - Implement copy trait (think C's memcpy) - use Cow<T> (Copy on Write) to semi-automatically manage copying
0
1
10
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 43: Besides std::HashMap, Rust has other #hashmap variants available for specific use cases: - IndexMap (indexmap crate): Maintains the insertion order of keys - BTreeMap (std::collections): Maintains elements in key-sorted order. - DashMap (dashmap crate):
1
2
9
@rustoftheday
Daily Rust
7 months
🦀 #Rust #Sunday #crate 12: poem-openapi might be worth looking into as an alternative to an Actis / Axum. It supports the #OpenAPI V3 specification, on of the advantages of which is automatic generation of documentation.
0
2
8
@rustoftheday
Daily Rust
7 months
@apollolabsbin I really, really don't get this argument. How do people put up with C++? Those compile times are 10x worse.
0
0
9
@rustoftheday
Daily Rust
6 months
@eloffd Source files with mixed tabs and spaces
1
0
9
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 32: What is #dynamic #dispatch ? In simple terms, it is the capability of handling different types at #runtime dynamically, via a common trait, thereby enabling (rust-flavored) #polymorphism . Box<dyn Trait> usually indicates the use of dynamic dispatch.
0
2
9
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 38: Working on a function but not ready to finalize? Use the todo!() or unimplemented!() macros to keep your code compiling. Just remember, your program will #panic at runtime if it hits these points! Ideal for development stages. 🚧
0
0
8
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 25: Exploring #smart #pointers : - Box<T> is for exclusive ownership, it gets freed once the context {} ends. -Rc<T> is a reference-counted smart pointer. It gets freed once no more references to it exist. -Arc<T> is a thread-safe variant of Rc<T>
0
1
8
@rustoftheday
Daily Rust
10 months
@Archie_Amari I'm already sold on #Rust . Can you point out any resources to get started in the Rust+ #LLM world?
4
0
8
@rustoftheday
Daily Rust
8 months
🦀 #daily #Rust 53. Continuing the theme of "core" or "system" #traits , the Drop trait is very interesting: Drop() will get called automatically for any data type that goes of of scope. So if you implement Drop(), it is possible to perform custom #cleanup operations if required.
0
0
8
@rustoftheday
Daily Rust
9 months
🦀 #daily #Rust 35: What are #trait #bounds ? We speak of trait bounds when we pass additional trait names to functions with generic arguments, to constrain the generic type: fn some_function<T: TraitA + TraitB>(param: T) { ... } You can combine multiple traits using the "+"
0
0
7
@rustoftheday
Daily Rust
7 months
🦀 #Rust #Sunday #crate 15: The Futures crate provides almost indispensable functionality for dealing with (who guessed it) futures in async environments.
Tweet media one
0
1
7
@rustoftheday
Daily Rust
7 months
@seanbax I would really welcome this for C++. It is a nice language. However, after experiencing Rust, getting an unexpected segfault after channeling my inner borrow-checker on a recent C++ project really p***ed me off 🙂
0
1
7
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 28: Rust #range expressions 1/2: - Inclusive range (contains a up to and incl. b) : a..=b - Exclusive range (contains a up to b-1) : a..b - From a : a.. - Up to b-1 : ..b - Up to and incl. b: ..=b - Full range: ..
0
0
7
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 29: Rust #range expressions 2/2: Range expressions can be applied to for loops, or used to create #iterators . Don't forget to call collect() to actually make the iterator execute:
Tweet media one
0
1
6
@rustoftheday
Daily Rust
8 months
@PatrickJS__ Ditch all that next.js stuff
0
0
5
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 33: Is let a: Arc<Mutex<Vec<f32>>> bothering you visually? Enter the type keyword, which lets you define type #aliases : type SharedSafeVec = Arc<Mutex<Vec<T>>> Then you can write: let a: SharedSafeVec<f32> #RustLang #CodeSimplicity
0
0
6
@rustoftheday
Daily Rust
7 months
🦀 #daily #Rust 77: A question about concurrency.
Threads > Async
24
Async > Threads
29
Depends (add reply)
36
4
0
6
@rustoftheday
Daily Rust
7 months
@shuttle_dev Leptos+Htmx
0
0
5
@rustoftheday
Daily Rust
7 months
@cleancodestudio Rust monads ≈ "rich enums"
0
0
5
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 31: If you need to pass a #vector non-mutably to a function, you can use &[T] (≡ &Vec<t>) arguments, which is also known as a #slice . Slice advantages: they avoid ownership transfer and are safe for #concurrent or #parallel operations.
0
0
5
@rustoftheday
Daily Rust
9 months
🦀 #Rust #Sunday #crate 5: "Mommy, can we buy #Python ? No, son, we have Python at home!" Check out the pyo3 crate, which lets you write Python🐍 in your Rust 🦀 code:
0
1
5
@rustoftheday
Daily Rust
9 months
🦀 #daily #rust 26: #Traits in Rust work similar to #interface definitions in other languages. Structs or enums that implement a trait are contractually bound to provide a #function with the signature specified in the trait.
Tweet media one
0
0
5
@rustoftheday
Daily Rust
9 months
@kiyov09 And tomorrow is Box<> ing day 😎
0
0
4
@rustoftheday
Daily Rust
8 months
0
0
4
@rustoftheday
Daily Rust
7 months
@Dev_AbdulHaseeb Neither: I would propose the word "craftsmanship". We're all glorified bit-plumbers when coding.
0
0
4
@rustoftheday
Daily Rust
8 months
@SynopticPixel @rabbit_hmi Sorry, how is it going to control my computer?
1
0
4
@rustoftheday
Daily Rust
8 months
@ChShersh I like to call Option<T> / Result<T> style wrapping enums "Rich Enums" 😆
1
0
4
@rustoftheday
Daily Rust
8 months
🦀🎇 #Rust #Sunday #crate 8: Are your for loops taking too long? Are 9 of your #CPU cores idle while you wait for results to manifest? Check out the Rayon crate to take advantage of #parallelization in a simple way:
0
0
3
@rustoftheday
Daily Rust
9 months
🦀🎄 #Rust #Sunday #crate 7: Take a look at the Nom crate: it makes it easy to create data readers where you are dealing with #binary data or #regular #expressions just don't cut it anymore:
Tweet media one
0
0
2
@rustoftheday
Daily Rust
7 months
@sentinel1909 Since we already have Rust, where do you reckon it fits into the stack? Python replacement?
2
0
2
@rustoftheday
Daily Rust
10 months
🦀 #daily #rust 16: Hey, you have some fine #HashMaps there, how do I #initialize them? Besides creating a new HashMap and inserting keys and values, one notable way is to use an array of tuples and an #iterator :
Tweet media one
0
0
3