#rust30by30 — Public Fediverse posts
Live and recent posts from across the Fediverse tagged #rust30by30, aggregated by home.social.
-
🤝 #Rustlang Tip: Contribute to the Rust community!
✅ DO:
- Report bugs you encounter
- Help answer questions on forums like users.rust-lang.org
- Contribute to open-source Rust projects
- Write blog posts or tutorials about your Rust experiences❌ DON'T:
- Be afraid to ask for help
- Hesitate to share your knowledge, no matter your skill levelRemember: Every contribution, big or small, helps the Rust ecosystem grow! 🦀
-
#Rustlang Tip:
✅ DO: use &str for string slices and String for owned strings.
❌ DON'T: use &String as a function parameter.Why? Using &str is more flexible:
1: It allows passing &str and &String as arguments.
2: It's more flexible as it can be used to pass string literals and string slices.
3: It clearly communicates that the function won't modify the string. -
🔁 #Rustlang Tip: Use the std::iter module for powerful iterator operations.
-
🔒 #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.
Sidenote: The #[non_exhaustive] attribute forces people to have a _ pattern in their matches that will match any new items you add later.
-
📚 #Rustlang Tip: Use cargo doc to generate documentation for your project.
Doc comments use three slashes /// and support Markdown
They appear in the generated documentation
Regular double line comments // won't be included in the documentation.example:
Run cargo doc --open to generate and view your documentation! -
✅ 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 Tip: Use the #[must_use] attribute to ensure important return values aren't ignored.
Result is already marked as must_use but other types can be too!
It's good to add #[must_use] when ignoring the return value of a function is almost always a bug.Reference: https://std-dev-guide.rust-lang.org/policy/must-use.html
-
🔍 #Rustlang Tip: Use the std::fmt::Display trait to customize how your structs are printed!
-
🔍 #Rustlang Tip: Use std::mem::size_of::<T>() to check the size of types at compile-time.
-
🔍 #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.
This is a performance optimization and shouldn't change the behavior of the code in most situations.
Be careful though, if you overestimate the size of the vector you will waste memory!
-
🧪 #Rustlang Tip: Use #[test] with #[ignore] for long-running or resource-intensive tests.
Run all tests: cargo test
Run ignored tests: cargo test -- --ignoredThis helps keep your test suite fast while still allowing those long running tests when needed!
-
🔍 #Rustlang Tip: Use cargo clippy to catch common mistakes and improve your code quality.
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 not only the code its linting but also your skills as a Rust developer!
You can enable Clippy as the default linter in VS Code by adding the JSON from the screenshot below to your settings.json file.
-
⚡ #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: https://docs.rs/crate/cargo-expand/0.1.3/source/README.md
-
🎨 Rust Tip: Use cargo fmt to automatically format your code according to Rust style guidelines.
📝 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 the settingOr you can add the following to your settings.json:
Link to ref: https://users.rust-lang.org/t/how-to-active-format-on-save-with-rust-analyzer-for-vs-code/41701
-
🏗️ #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!
-
🏗️ #Rustlang Tip: Use the #[derive(Default)] attribute for struct initialization if all your fields have a Default implementation.
Be careful though, sometimes the Default implementation is not what you want!
For instance, if you have a String field, the default implementation will create an empty string, which if often not what I want.
In those cases you can implement Default manually for custom behavior.
-
⚡ #Rustlang Tip: use Option<T> for values that might be absent.
Rust doesn't have null values, but it does have Option<T>, which is an enum that represents a value that might be present or absent.
This lets the compiler help check for those pesky "null" cases for you, and make sure you handle the Option::None case!
-
⚡ #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 when you make changes to your code.
-
🔧 #Rustlang Tip
Use the #[derive(Debug, Clone)] attribute to automatically generate implementations for the Debug and Clone traits for your structs and enums!💡 Clone is useful when you need a copy of the struct
💡 Debug is useful for printing the struct for debugging purposes, and can be used with the dbg! macro -
⚠️ #RustLang Tip: Don't use .unwrap()!
Use expect() instead in tests or when you're absolutely sure a Result/Option is Some/Ok but you can't convey that in the type system.
❌ DON'T: Use either in production code where errors are possible.expect() is like unwrap() but with a custom message!
🔍 Better alternatives:
• ❓ ? operator, to forward the error up the call stack
• 🧩 match📚 Read more: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
-
🧩 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! -
🧪 #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 #TDDRun `cargo test` to see the output!
Learn more: https://doc.rust-lang.org/book/ch11-01-writing-tests.html -
🐞 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!
-
🔄 You can swap two values without creating a temp variable!
```rust
let a = 1;
let b = 2;
let (a, b) = (b, a);
println!("{}, {}",a,b);
//output: 2, 1
```
#Rust30by30 #Rust #Rustlang #Day1