about
03/26/2023
RustBites - CodeExamples
Rust Bite - Code Examples
links to all the RustBites code examples
Table of Examples
Bite | Link | Content |
---|---|---|
Introduction | Hello | Visual Studio Code views of "Hello World" code, build and output, and associated metadata in Cargo.toml |
GettingStarted | Functions | simple demos: iterator, factorial, methods for construction and retrieval |
UDB | Undefined behavior | Shows how undefined behavior can occur using C++: refs to unowned memory, index out of bounds. Also shows how Rust eliminates these behaviors by compiler analysis and run-time checks. |
Data | Data operations | Many small code fragments throughout page, illustrating data operations: bind, copy, move, clone. |
FlashCards | Rust Collections | Small code fragments showing how to initialize Rust collection types and push a few data items, with diagrams illustrating collection structure. |
Facts | Survey | Tables summarizing data operations, data structures, smart pointers, ownership rules, and generics with small code fragments. |
Strings | Examples for &str | str is the type of a literal string, a Copy type, and &str is a reference to that. |
Strings | Examples for String | String is a Move type composed of a collection of utf8 characters. |
Strings | Examples for String iteration | Iteration must work with characters that vary in size from 1 to 4 bytes. |
DataStr | Primitives and Aggregates | Code fragments for construction and initialization. |
DataStr | Iterators | Code fragments for iteration over collections and very useful iterator methods. Also has examples of use. |
DataStr | String | Examples of formatting for output using iterators. |
DataStr | Vec<T> | Examples of initialization, manipulation, and iteration. |
DataStr | HashMap<K,V> | Examples of associative collection - initialization, manipulation, and iteration. |
SmartPtrs | Box<T> | Example of pointer to item in heap - creation and lifecycle of its data. |
SmartPtrs | Rc<T> | Example of ref counted ptr - creation and use referring to multiple items. |
SmartPtrs | Arc<T> | Example of thread-safe ref counted ptr - creation and use referring to multiple items. |
SmartPtrs | RefCell<T> | Example of ptr with interior mutability - shows run-time borrow checking. |
SmartPtrs | Other interesting problems | Solutions to 3 problems that illustrate use of SmartPtrs. |
LifeCycle | TestLifeCycle | User-defined Type and Vec: instance creation, clone, use, move, and drop |
Ownership | Strings and string references | Examples of ownership and demonstration of errors |
Traits | Demonstrate generics and traits | Simple examples of a generic function and struct. Summary of frequently used traits. |
Functs | Passing arguments | Examples of pass-by-value and pass-by-reference |
Functs | Return types | Examples of Option<T> and Result<T,E> return types |
Functs | Generics | Generic function that can process a variety of collection types. |
Functs | Closures | Explores captured data, moves, and use with iterator methods. Also has example of function accepting a closure. |
Structs | User-defined types | Examples of creating non-generic and generic types. |
Structs | Traits | Example trait and its use building a Point<T> type. |
Structs | Dispatch | Example of static dispatch vs dynamic dispatch using trait. |
LifeTime | lifetime annotation | Example showing when lifetime annotation is needed, via compiler error messages, and how to supply the annotation. |
Enums | User-defined enumerations | Example of an Event<T> enumeration - definition and use. |
Enums | Matching | Matching, usually used with enums, is illustrated here with character ranges to build a partial lexer. |
ErrHnd | Result<T,E> & Option<T> | Simple demonstration of error and optional handling with matching. |
ErrHnd | Bubbling errors up to caller | Bubbling up errors dramatically reduces redundant error handling code. |
Options | Iterators use Option<T> | Illustrates how plain loops and for-loops work. |
Options | Iterating over generic types | Illustrates displaying Rust types and functions that accept iterators. |
Options | Plug-ins | Illustrates role of Option<T> and traits in building plug-in architectures. |
Collections | Some of the Rust collections | Diagrams and small code fragmentes illustrating use of arrays, tupls, structs, Vec<T>, VecDeque<T>, HashMap<K,V>, String, and str. Has links to playground code. |
Iterators | Functions that accept iterators | These functions use traits to accept any collection that has an iterator in order to view and manipulate the collection elements. Examples also show how to return an iterator and how to create a custom iterator type. Also has everal links to playground examples. |
Iterators | Iterating over utf8 strings | Text shows how String iteration works. Links are provided to playground examples. |
Iterators | Iterator adapters | Adapters support composing operations on collections during iteration. Table shows useful adapter signatures and links to examples in playground. |
Iterators | Loops | Example shows how for loop is implemented with iterators. |
Iterators | Ranges | Text provides definition and an example. Links to examples in playground. |
Iterators | Slices | Text provides definition and an example. Links to examples in playground. |
Idioms | Converting to idiomatic code | Idiomatic code conforms to Rust community accepted structure and style. One simple code example provided with explanation. Text adds additional information about clippy, a very useful cargo tool that reports non-idomatic code fragments. |
Macros | Declarative macros | Examples of capturing local data and building variatic operations using recursion. |
Macros | Macro structure | Example of macro with two expansion rules. |
Macros | Variadic macros | Example of variadic operation with detailed annotations. |
Macros | A practical example | Illustrates matching lexical categories. Builds a "time_it!" macro. Also provides a macro for building HashMaps. |
Macros | standard Rust macros | Partial list of standard macros with descriptions and examples. |
Macros | Macro arguments | Compares macro that consumes arguments vs one that does not. |
Threads | Interior mutability | Demonstrates interior mutability, essential for most threading applications. |
Threads | std::cell types | Illustrates use of UnsafeCell<T>, Cell<T>, and RefCell<T>. These codes are excerpts from std library documentation with my annotations. |
Threads | Basic threading | Child and main threads share std::output and AtomicUsize, both thread safe types. |
Threads | Sharing | Example of two threads sharing a non thread-safe String using Mutex<T> and Arc<T>. |
Threads | ThreadResult<T> | Code defines a ThreadResult<T> type using Mutex<T> and Condvar. ThreadResult instances are very similar to C++ future<T>, providing polling and blocking get. This provides a safe way for a thread to return a result to its creator. Note that Rust std::library defines a future associated with async processing. This is part of the infrastructure for async executers like Tokio. |
Threads | BlockingQueue<T> | Code defines a BlockingQueue<T> type using Mutex<VecDeque<T>> and Condvar. This thread-safe queue blocks dequers when empty and unblocks for deques when "messages" arrive. |
Synchron | Synchronization Types | Table describes and links to documentation with examples for Mutex<T>, RwLock<T>, Condvar, Atomic, Arc<T>, and Barrier. |
Synchron | Mutex<T> | Synchronizes access for two readers and two writers to a shared String. |
Synchron | RwLock<T> | Synchronizes access for four readers and two writers to a shared String. |
Synchron | Condvar<T> | Uses ThreadResult<T>, which uses Condvar, to poll and wait for results. |
Synchron | Atomics | Uses AtomicUsize to count operations in a thread's loop. |
Synchron | Barrier | Waits for all threads to start in a multi-threaded example. |
RegEx | Simple matching | Example uses two fairly simple regular expression strings for matching. |
RegEx | Important RegEx tokens | Table of important tokens with use example fragments. |
RegEx | RegEx crate | Examples of use for RegEx crate. |
TipsAndTricks | Member thread | Example of user-defined type with thread start method. |
TipsAndTricks | Start thread in constructor | Example of user-defined type with thread start in constructor. |
TipsAndTricks | Stop thread | Example of user-defined type with thread stop method - uses AtomicBool to signal. |
TipsAndTricks | Stop watch | Example of user-defined timer. |
TipsAndTricks | callback | Example of user-defined timer with callback. |
TipsAndTricks | DateTime stamps | Example of DateTime stamps in several formats. |
CodeExperiments | Experimenting with Playground | Using Rust Playground to experiment with code in an organized way. |
CodeExperiments | Simple Playground Experiments | A set of basic demos in Rust Playground. |
Rust Glossary of Terms | Rust terms defined | Rust terms defined with text and code examples. |