Rust code snippets with use cases
29 ready-made code building blocks, sorted by topic.
Data structures
- Working with a Vec – Managing collections of values: adding, sorting, filtering.
- HashMap – Storing mappings, e.g. configurations or counters.
- Sorting structs – Ordering records by a field, e.g. users by age.
OOP
- Struct + trait instead of a class – Bundling data and behavior, e.g. users, products, game characters.
- Enum with data and match – Modeling states or commands (commands, messages, parser tokens); the compiler checks…
- Struct with derive and Default – Configuration objects with sensible default values and simple debug output.
Error handling
- Handling a Result – Guarding user input or file access without crashing the program.
- Using Option safely – Modeling values that may be missing (search, configuration, first element) without null…
- Custom error type with From and ? – Passing several kinds of errors (file, parsing) on uniformly within one function.
Memory
- Trait objects with Box<dyn Trait> – Keeping different types with the same behavior in one list (plugins, shapes, handlers).
- Shared mutable data (Rc<RefCell>) – Several owners modifying the same data structure (graphs, GUI state) within one thread.
- Function with a lifetime annotation – Returning references that depend on several inputs (search, longest text).
Concurrency
- Distributing a computation across threads – Spreading compute-intensive tasks (sums, image processing) across several cores.
- Shared counter with Arc<Mutex> – Sharing state between threads, e.g. statistics or caches in a server.
- Messages between threads (channel) – Worker threads deliver results to a collector (pipeline, job queue).
More snippets
- Hello World – A first test of whether Rust is installed correctly.
- Variables and types – Storing values; types are fixed, and mutability must be allowed explicitly.
- if / else if / else – Reacting differently, e.g. calculating grades or price tiers.
- for loop – Processing every element of a list or repeating n times.
- Function with a return value – Bundling recurring logic, e.g. greeting texts or calculations.
- Reading and writing a file – Saving and loading logs, configurations, or text data.
- Reading a file line by line – Processing large log files without loading everything into memory.
- Generic function with a trait bound – Writing one function for many types (output, comparison, sums) without duplicating code.
- Display for your own types – Printing your own types nicely, e.g. in logs or error messages.
- Iterator chains – Filtering, transforming, and aggregating data, e.g. evaluating prices or measurements.
- Splitting and parsing a CSV line – Converting simple text formats (CSV, log lines, config entries) into values.
- Counting words – Text analysis, e.g. the most frequent words in a document.
- Command-line arguments – Building your own CLI tools that accept names, files, or options.
- Writing a unit test – Checking functions automatically so that refactorings do not introduce bugs.