Trending

#Rust30by30

Latest posts tagged with #Rust30by30 on Bluesky

Latest Top
Trending

Posts tagged #Rust30by30

🀝 #Rustlang Tip: Contribute to the Rust community!

❌ DON'T:

- Be afraid to ask for help
- Hesitate to share your knowledge, no matter your skill level

Remember: Every contribution, big or small, helps the Rust ecosystem grow! πŸ¦€

#Rust30by30

3 1 0 0
let nums = vec![1, 2, 3, 4, 5];
let sum: i32 = nums.iter().filter(|x| *x % 2 == 0).sum();
println!("Sum: {}", sum);

let nums = vec![1, 2, 3, 4, 5]; let sum: i32 = nums.iter().filter(|x| *x % 2 == 0).sum(); println!("Sum: {}", sum);

πŸ” #Rustlang Tip: Use the std::iter module for powerful iterator operations.

Docs: https://doc.rust-lang.org/std/iter/

#Rust30by30

3 0 0 0
#[non_exhaustive]
pub enum Color {
    Red,
    Green,
    Blue,
}

fn main() {
    let color = Color::Red;
    match color {
        Color::Red => println!("It's red!"),
        Color::Green => println!("It's green!"),
        Color::Blue => println!("It's blue!"),
        _ => println!("It's a new color!"),
    }
}

#[non_exhaustive] pub enum Color { Red, Green, Blue, } fn main() { let color = Color::Red; match color { Color::Red => println!("It's red!"), Color::Green => println!("It's green!"), Color::Blue => println!("It's blue!"), _ => println!("It's a new color!"), } }

πŸ”’ #Rustlang Tip: Use the #[non_exhaustive] attribute for future-proofing your enums and structs.

This allows you to add new variants later without breaking existing code.

This attribute forces people to have a _ pattern in their matches that will match any items you add later.

#Rust30by30

4 0 0 0
/// The `add` function adds two numbers
///
/// # Examples
///
/// let result = add(2, 3);
/// assert_eq!(result, 5);
///
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// The `add` function adds two numbers /// /// # Examples /// /// let result = add(2, 3); /// assert_eq!(result, 5); /// pub fn add(a: i32, b: i32) -> i32 { a + b }

πŸ“š #Rustlang Tip: Use cargo doc to generate docs for your project

Doc comments use three slashes /// and support Markdown
They appear in the generated documentation
Regular won't be included in the documentation.

example:
Run `cargo doc --open` to generate and view your documentation!

#Rust30by30

1 0 0 0

βœ… DO: Use std::collections::HashSet for storing unique values.
❌ DON'T: Reinvent the wheel with custom data structures.

Sidenote: A HashSet is implemented as a HashMap where the value is the empty tuple (). So HashSet<String> is essentially the same as HashMap<String, ()>!

#Rustlang #Rust30by30

2 0 0 0
struct Person { name: String, age: u32 }  impl std::fmt::Display for Person {     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {         write!(f, "{} ({} years old)", self.name, self.age)     } }  fn main() {     let person = Person { name: "Alice".to_string(), age: 30 };     println!("{}", person);     // Output: Alice (30 years old) }

struct Person { name: String, age: u32 } impl std::fmt::Display for Person { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{} ({} years old)", self.name, self.age) } } fn main() { let person = Person { name: "Alice".to_string(), age: 30 }; println!("{}", person); // Output: Alice (30 years old) }

πŸ” #Rustlang Tip: Use the std::fmt::Display trait to customize how your structs are printed!

#RustFormatting #Rust30by30 #Day18

0 0 0 0
println!("Size of i32: {}", std::mem::size_of::<i32>()); //output: Size of i32: 4 println!("Size of i64: {}", std::mem::size_of::<i64>()); //output: Size of i64: 8 println!("Size of String: {}", std::mem::size_of::<String>()); //output: Size of String: 24

println!("Size of i32: {}", std::mem::size_of::<i32>()); //output: Size of i32: 4 println!("Size of i64: {}", std::mem::size_of::<i64>()); //output: Size of i64: 8 println!("Size of String: {}", std::mem::size_of::<String>()); //output: Size of String: 24

πŸ” #Rustlang Tip: Use std::mem::size_of::<T>() to check the size of types at compile-time.

#RustPerformance #Rust30by30 #Day17

0 0 0 0
let mut vec = Vec::with_capacity(10); for i in 0..10 {     vec.push(i); }

let mut vec = Vec::with_capacity(10); for i in 0..10 { vec.push(i); }

πŸ” #Rustlang Tip: Use Vec::with_capacity(n) when you know the approximate size of your vector beforehand. This will reserve memory for the vector to avoid multiple allocations.

Be careful though, if you overestimate the size of the vector you will waste memory!

#RustCollections #Rust30by30 #Day16

0 0 0 0
#[cfg(test)] mod tests {     use std::thread;     use std::time::Duration;      #[test]     fn quick_test() {         assert_eq!(2 + 2, 4);     }      #[test]     #[ignore]     fn slow_test() {         // Simulate a long-running test         thread::sleep(Duration::from_secs(5));         assert!(true);     } }

#[cfg(test)] mod tests { use std::thread; use std::time::Duration; #[test] fn quick_test() { assert_eq!(2 + 2, 4); } #[test] #[ignore] fn slow_test() { // Simulate a long-running test thread::sleep(Duration::from_secs(5)); assert!(true); } }

πŸ§ͺ #Rustlang Tip: Use #[test] with #[ignore] for long-running or resource-intensive tests.

Run all tests: cargo test
Run ignored tests: cargo test -- --ignored

This helps keep your test suite fast while still allowing those long running tests when needed!

#RustTesting #Rust30by30 #Day15

3 0 0 0
"rust-analyzer.check.command": "clippy"

"rust-analyzer.check.command": "clippy"

πŸ” #Rustlang Tip: Use cargo clippy to catch common mistakes and improve your code!

It's also a great learning tool! It will show you best practices to follow, and by reading and understanding the suggestions you can improve your skills as a Rust developer!

#Rust30by30 #Day14

1 0 0 0
macro_rules! create_function {     ($func_name:ident) => {         fn $func_name() {             println!("You called {:?}()", stringify!($func_name));         }     }; }  create_function!(foo); create_function!(bar);  fn main() {     foo();     bar(); }

macro_rules! create_function { ($func_name:ident) => { fn $func_name() { println!("You called {:?}()", stringify!($func_name)); } }; } create_function!(foo); create_function!(bar); fn main() { foo(); bar(); }

// notice how all the imports are revealed! #![feature(prelude_import)] #[prelude_import] use std::prelude::rust_2021::*; #[macro_use] extern crate std;  // notice how the function bodies are shown! fn foo() {     {         ::std::io::_print(format_args!("You called {0:?}()\n", "foo"));     }; } fn bar() {     {         ::std::io::_print(format_args!("You called {0:?}()\n", "bar"));     }; } fn main() {     foo();     bar(); }

// notice how all the imports are revealed! #![feature(prelude_import)] #[prelude_import] use std::prelude::rust_2021::*; #[macro_use] extern crate std; // notice how the function bodies are shown! fn foo() { { ::std::io::_print(format_args!("You called {0:?}()\n", "foo")); }; } fn bar() { { ::std::io::_print(format_args!("You called {0:?}()\n", "bar")); }; } fn main() { foo(); bar(); }

⚑ #Rustlang Tip: cargo expand - Your X-ray Vision for Macros

cargo expand allows you to see the expanded code generated by macros, providing more insight into what's happening under the hood

Learn more here: docs.rs/crate/cargo-expand/0.1.3...

#RustMacros #Rust30by30 #Day13

0 0 0 0
Preview
How to active format on save with rust-analyzer for VS Code? I have used rust-analyzer on VS Code for a while now but I cannot find any settings key related to format on save.

🎨 Rust Tip: Use cargo fmt to automatically format your code!
πŸ“ You can even setup your editor to Auto-Format on save!

VS Code Instructions:

- Install the Rust Analyzer extension
- Open settings
- Search for "Format on Save" and enable it

#RustTips #Rust30by30 #Day12

2 0 0 0
struct Person {     name: String,     age: u32, }  fn main() {     let person = Person {         name: "rust biggest fan".to_string(),         ..Default::default()     };     println!("{:?}", person);     // Output: Person { name: "rust biggest fan", age: 0 } }

struct Person { name: String, age: u32, } fn main() { let person = Person { name: "rust biggest fan".to_string(), ..Default::default() }; println!("{:?}", person); // Output: Person { name: "rust biggest fan", age: 0 } }

πŸ—οΈ #Rustlang Hack: Use the ..Default::default() syntax to initialize structs with some default values while customizing others.

This is also not limited to Default::default() it will work with any instance of your struct!

#Rust30by30 #Day11

1 0 0 0
#[derive(Default, Debug)] struct Person {     name: String,     age: u32, }  #[derive(Debug)] struct PersonWithCustomDefault {     name: String,     age: u32, }  impl Default for PersonWithCustomDefault {     fn default() -> Self {         PersonWithCustomDefault { name: "Unknown".to_string(), age: 10 }     } }  fn main() {     let person = Person::default();     println!("{:?}", person);     // Output: Person { name: "", age: 0 }      let person_with_custom_default = PersonWithCustomDefault::default();     println!("{:?}", person_with_custom_default);     // Output: PersonWithCustomDefault { name: "Unknown", age: 10 } }

#[derive(Default, Debug)] struct Person { name: String, age: u32, } #[derive(Debug)] struct PersonWithCustomDefault { name: String, age: u32, } impl Default for PersonWithCustomDefault { fn default() -> Self { PersonWithCustomDefault { name: "Unknown".to_string(), age: 10 } } } fn main() { let person = Person::default(); println!("{:?}", person); // Output: Person { name: "", age: 0 } let person_with_custom_default = PersonWithCustomDefault::default(); println!("{:?}", person_with_custom_default); // Output: PersonWithCustomDefault { name: "Unknown", age: 10 } }

πŸ—οΈ #Rustlang Tip: Use the #[derive(Default)] attribute for struct initialization if all your fields have a Default implementation.

Be careful though, for Strings field, the default implementation will create an empty string!

#RustTricks #Rust30by30 #Day10

0 0 0 0
struct Animal {     name: String,     age: u32,     fav_treat: Option<String> }  fn print_treat(animal: Animal) {     // println!("{} loves {}", animal.name, animal.fav_treat)     // This line ^^ wouldn't compile because fav_treat is an Option<String>     // and can't be printed directly. Instead lets use a match statement!     match &animal.fav_treat {         Some(treat) => println!("{} loves {}", animal.name, treat),         None => println!("{} doesn't have a favorite treat", animal.name),     } }

struct Animal { name: String, age: u32, fav_treat: Option<String> } fn print_treat(animal: Animal) { // println!("{} loves {}", animal.name, animal.fav_treat) // This line ^^ wouldn't compile because fav_treat is an Option<String> // and can't be printed directly. Instead lets use a match statement! match &animal.fav_treat { Some(treat) => println!("{} loves {}", animal.name, treat), None => println!("{} doesn't have a favorite treat", animal.name), } }

⚑ #Rustlang Tip: use Option<T> for values that might be absent.

Rust doesn't have null values, but it does have Option<T>

This lets the compiler help check for those pesky "null" cases for you, and make sure you handle the Option::None case!

#RustTricks #Rust30by30 #Day9

1 0 0 0

⚑ #Rustlang Tip: Speed up dev cycles by using cargo check instead of cargo build during development

It skips building everything but still checks your code for any compilation errors!
You can also use cargo watch to automatically run cargo check!

#RustTricks #Rust30by30 #Day8

1 0 0 0
#[derive(Debug, Clone)] struct Person {     name: String,     age: u32, }  fn main() {     let alice = Person { name: "Alice".into(), age: 30 };     let mut bob = alice.clone();     bob.name = "Bob".to_string();      dbg!(alice);     dbg!(bob);     // Outputs:     // alice = Person { name: "Alice", age: 30 }     // bob = Person { name: "Bob", age: 30 } }

#[derive(Debug, Clone)] struct Person { name: String, age: u32, } fn main() { let alice = Person { name: "Alice".into(), age: 30 }; let mut bob = alice.clone(); bob.name = "Bob".to_string(); dbg!(alice); dbg!(bob); // Outputs: // alice = Person { name: "Alice", age: 30 } // bob = Person { name: "Bob", age: 30 } }

πŸ”§ #Rustlang Tip
Use the #[derive(Debug, Clone)] attribute to automatically generate implementations for the Debug and Clone traits.

πŸ’‘ Clone is useful when you need a copy of the struct
πŸ’‘ Debug is useful for printing the struct for debugging, try with dbg!

#Rust30by30 #Day6

1 0 0 0
Recoverable Errors with Result - The Rust Programming Language Most errors aren’t serious enough to require the program to stop entirely. Sometimes when a function fails it’s for a reason that you can easily interpret and respond to. For example, if you try to…

πŸ” Better alternatives:
β€’ ❓ ? operator, to forward the error up the call stack
β€’ 🧩 match

πŸ“š Read more: doc.rust-lang.org/book/ch09-02-recoverable...

#ErrorHandling #Rust30by30 #Day5

2/2

0 0 0 0
trait Printable {     fn print(&self); }  struct NewsArticleTitle(String); impl Printable for NewsArticleTitle {     fn print(&self) {         println!("News Article: {}", self.0);     } }  struct BlogPostTitle(String); impl Printable for BlogPostTitle {     fn print(&self) {         println!("Blog Post: {}", self.0);     } }  fn print_me<P: Printable>(item: P) {     item.print(); }  fn main() {     let article = NewsArticleTitle("Breaking News - Rust is fun!".to_string());     let post = BlogPostTitle("Why I love Rust!".to_string());     print_me(article);     print_me(post); } // Outputs: // News Article: Breaking News - Rust is fun! // Blog Post: Why I love Rust!

trait Printable { fn print(&self); } struct NewsArticleTitle(String); impl Printable for NewsArticleTitle { fn print(&self) { println!("News Article: {}", self.0); } } struct BlogPostTitle(String); impl Printable for BlogPostTitle { fn print(&self) { println!("Blog Post: {}", self.0); } } fn print_me<P: Printable>(item: P) { item.print(); } fn main() { let article = NewsArticleTitle("Breaking News - Rust is fun!".to_string()); let post = BlogPostTitle("Why I love Rust!".to_string()); print_me(article); print_me(post); } // Outputs: // News Article: Breaking News - Rust is fun! // Blog Post: Why I love Rust!

🧩 Traits are not for method overloading.
They are a way to define methods that multiple types can implement, enabling polymorphism!

With traits you can write functions that accept different types, that all have a common behavior.
All while maintaining type safety!

#Rust30by30 #Rustlang #Day4

1 0 0 0
fn fibonacci(n: u64) -> u64 {     if n <= 1 {         return n;     }     fibonacci(n - 1) + fibonacci(n - 2) }  #[cfg(test)] mod tests {     use super::*;      #[test]     fn test_fibonacci() {         assert_eq!(fibonacci(0), 0);         assert_eq!(fibonacci(1), 1);         assert_eq!(fibonacci(2), 1);         assert_eq!(fibonacci(10), 55);     } }

fn fibonacci(n: u64) -> u64 { if n <= 1 { return n; } fibonacci(n - 1) + fibonacci(n - 2) } #[cfg(test)] mod tests { use super::*; #[test] fn test_fibonacci() { assert_eq!(fibonacci(0), 0); assert_eq!(fibonacci(1), 1); assert_eq!(fibonacci(2), 1); assert_eq!(fibonacci(10), 55); } }

πŸ§ͺ #RustLang Tip

βœ… DO: Use Rust's built-in testing framework to write unit tests and integration tests.
❌ DON'T: Skip testing, it's crucial for maintainable code! #RustTesting #TDD

Run `cargo test` to see the output!
Learn more: https://buff.ly/3XZHtbu

#Rust30by30 #Day3

0 0 0 0
let x = 5; let y = 10; dbg!(x + y); //output: [src/main.rs:3] x + y = 15

let x = 5; let y = 10; dbg!(x + y); //output: [src/main.rs:3] x + y = 15

🐞 Rust Hack: Use the `dbg!` macro to print variables and expressions during debugging. No more `println!` with manual variable names!

You even get the file and line number, for free!

#Rustlang #Debugging #Rust30by30 #Day2

4 0 0 0
let a = 1; let b = 2; let (a, b) = (b, a); println!("{}, {}",a,b); //output: 2, 1

let a = 1; let b = 2; let (a, b) = (b, a); println!("{}, {}",a,b); //output: 2, 1

πŸ”„ You can swap two values with creating a temp variable!

```rust
let a = 1;
let b = 2;
let (a, b) = (b, a);
println!("{}, {}",a,b);
//output: 2, 1
```
#Rust30by30 #Rustc #Rustlang #Day1

0 0 1 0