### Rust Struct with Methods and Example Source: https://rust-unofficial.github.io/patterns/idioms/rustdoc-init.html Demonstrates a Rust struct 'Connection' with a 'send_request' method and its associated example, including necessary boilerplate for testing. ```rust struct Connection { name: String, stream: TcpStream, } impl Connection { /// Sends a request over the connection. /// /// # Example /// ```no_run /// # // Boilerplate are required to get an example working. /// # let stream = TcpStream::connect("127.0.0.1:34254"); /// # let connection = Connection { name: "foo".to_owned(), stream }; /// # let request = Request::new("RequestId", RequestType::Get, "payload"); /// let response = connection.send_request(request); /// assert!(response.is_ok()); /// ``` fn send_request(&self, request: Request) -> Result { // ... } /// Oh no, all that boilerplate needs to be repeated here! fn check_status(&self) -> Status { // ... } } ``` -------------------------------- ### Rust Struct with Helper Function for Examples Source: https://rust-unofficial.github.io/patterns/idioms/rustdoc-init.html Illustrates a Rust struct 'Connection' with a 'send_request' method, using a wrapping helper function to simplify examples and avoid repetitive boilerplate. ```rust struct Connection { name: String, stream: TcpStream, } impl Connection { /// Sends a request over the connection. /// /// # Example /// ``` /// # fn call_send(connection: Connection, request: Request) { /// let response = connection.send_request(request); /// assert!(response.is_ok()); /// # } /// ``` fn send_request(&self, request: Request) -> Result { // ... } } ``` -------------------------------- ### Rust Serialization and Deserialization Example Source: https://rust-unofficial.github.io/patterns/print.html Demonstrates serializing a Rust struct to JSON and then deserializing it back using generated visitor types and macros. ```rust fn main() { let a = TestStruct { a: 5, b: "hello".to_string() }; let a_data = a.serialize().to_json(); println!("Our Test Struct as JSON: {a_data}"); let b = TestStruct::deserialize( generated_visitor_for!(TestStruct)::from_json(a_data)); } ``` -------------------------------- ### Concordance Serialization/Deserialization Example Source: https://rust-unofficial.github.io/patterns/functional/optics.html A basic Rust implementation for serializing and deserializing a custom `Concordance` struct to and from a String. This serves as a practical example for the Iso pattern. ```rust #![allow(unused)] fn main() { use std::collections::HashMap; struct Concordance { keys: HashMap, value_table: Vec<(usize, usize)> M } struct ConcordanceSerde {} impl ConcordanceSerde { fn serialize(value: Concordance) -> String { todo!() } // invalid concordances are empty fn deserialize(value: String) -> Concordance { todo!() } } } ``` -------------------------------- ### JSON Deserialization Example Source: https://rust-unofficial.github.io/patterns/print.html Demonstrates how to deserialize a JSON string into a Rust struct using Serde's derive macro. ```APIDOC ## JSON Deserialization Example ### Description This example shows how to use Serde's `Deserialize` derive macro to automatically generate the implementation for deserializing a JSON string into a Rust struct. ### Request Body Example (JSON) ```json { "name": "Alice", "customer_id": "12345" } ``` ### Rust Struct Definition ```rust use serde::Deserialize; #[derive(Deserialize)] struct IdRecord { name: String, customer_id: String, } ``` ### Usage To deserialize the JSON above into an `IdRecord` struct, you would typically use a JSON deserializer provided by Serde: ```rust use serde::Deserialize; #[derive(Deserialize)] struct IdRecord { name: String, customer_id: String, } fn main() { let json_data = r#"{ "name": "Alice", "customer_id": "12345" }"#; // Using serde_json::from_str to deserialize let record: Result = serde_json::from_str(json_data); match record { Ok(id_record) => { println!("Name: {}", id_record.name); println!("Customer ID: {}", id_record.customer_id); } Err(e) => { eprintln!("Deserialization error: {}", e); } } } ``` ### Response Example (Success) If deserialization is successful, you will have an `IdRecord` instance: ```rust // Inside the main function, after successful deserialization: // Name: Alice // Customer ID: 12345 ``` ``` -------------------------------- ### Embedded HAL Pin Mode Example Source: https://rust-unofficial.github.io/patterns/print.html This example from the `embedded-hal` ecosystem shows how a pin's generic type determines its usable functions based on its mode. ```Rust struct PA0 ``` -------------------------------- ### Using Serde Derive and Visitor Macros Source: https://rust-unofficial.github.io/patterns/functional/optics.html Example demonstrating the usage of `serialize` and `deserialize` methods on `TestStruct` after applying `#[derive(Serde)]` and using a hypothetical `generated_visitor_for!` macro. ```rust fn main() { let a = TestStruct { a: 5, b: "hello".to_string() }; let a_data = a.serialize().to_json(); println!("Our Test Struct as JSON: {a_data}"); let b = TestStruct::deserialize( generated_visitor_for!(TestStruct)::from_json(a_data)); } ``` -------------------------------- ### Hyper Client API Example Source: https://rust-unofficial.github.io/patterns/print.html The `hyper` HTTP client library uses this pattern to provide different methods and trait implementations for clients with various connectors. ```Rust struct Client ``` -------------------------------- ### Rust Implementation of FromStr and ToString Source: https://rust-unofficial.github.io/patterns/print.html Example implementation of FromStr and ToString for a custom struct in Rust. Note the use of `todo!()` indicating incomplete implementation. ```rust use anyhow; use std::str::FromStr; struct TestStruct { a: usize, b: String, } impl FromStr for TestStruct { type Err = anyhow::Error; fn from_str(s: &str) -> Result { todo!() } } impl ToString for TestStruct { fn to_string(&self) -> String { todo!() } } fn main() { let a = TestStruct { a: 5, b: "hello".to_string(), }; println!("Our Test Struct as JSON: {}", a.to_string()); } ``` -------------------------------- ### Implement Strategy Pattern in Rust Source: https://rust-unofficial.github.io/patterns/patterns/behavioural/strategy.html Demonstrates the Strategy pattern using Rust traits and structs. This example shows how to create interchangeable algorithms for report formatting (Text and Json) that can be selected at runtime. ```Rust use std::collections::HashMap; type Data = HashMap; trait Formatter { fn format(&self, data: &Data, buf: &mut String); } struct Report; impl Report { // Write should be used but we kept it as String to ignore error handling fn generate(g: T, s: &mut String) { // backend operations... let mut data = HashMap::new(); data.insert("one".to_string(), 1); data.insert("two".to_string(), 2); // generate report g.format(&data, s); } } struct Text; impl Formatter for Text { fn format(&self, data: &Data, buf: &mut String) { for (k, v) in data { let entry = format!( K " {v}\n"); buf.push_str(&entry); } } } struct Json; impl Formatter for Json { fn format(&self, data: &Data, buf: &mut String) { buf.push('['); for (k, v) in data.into_iter() { let entry = format!(r#"{{"{}":"{}"}}"#, k, v); buf.push_str(&entry); buf.push(','); } if !data.is_empty() { buf.pop(); // remove extra , at the end } buf.push(']'); } } fn main() { let mut s = String::from(""); Report::generate(Text, &mut s); assert!(s.contains("one 1")); assert!(s.contains("two 2")); s.clear(); // reuse the same buffer Report::generate(Json, &mut s); assert!(s.contains(r#"{{"one":"1"}}"#)); assert!(s.contains(r#"{{"two":"2"}}"#)); } ``` -------------------------------- ### Java Inheritance Example Source: https://rust-unofficial.github.io/patterns/anti_patterns/deref.html Illustrates a common inheritance pattern in Java where a subclass inherits methods from a superclass. ```java class Foo { void m() { ... } } class Bar extends Foo {} public static void main(String[] args) { Bar b = new Bar(); b.m(); } ``` -------------------------------- ### Adding Protocol-Specific Fields (NFS Example) Source: https://rust-unofficial.github.io/patterns/functional/generics-type-classes.html Extending the struct to include protocol-specific fields like `mount_point` for NFS. This necessitates runtime checks in methods like `mount_point()`. ```Rust struct FileDownloadRequest { file_name: PathBuf, authentication: AuthInfo, mount_point: Option, } impl FileDownloadRequest { // ... other methods ... /// Gets an NFS mount point if this is an NFS request. Otherwise, /// return None. pub fn mount_point(&self) -> Option<&Path> { self.mount_point.as_ref() } } ``` -------------------------------- ### Implementing FromStr and ToString for TestStruct Source: https://rust-unofficial.github.io/patterns/functional/optics.html An example of implementing `FromStr` and `ToString` traits for a custom `TestStruct` in Rust. Note that `todo!()` is used as a placeholder for actual implementation. ```rust use anyhow; use std::str::FromStr; struct TestStruct { a: usize, b: String, } impl FromStr for TestStruct { type Err = anyhow::Error; fn from_str(s: &str) -> Result { todo!() } } impl ToString for TestStruct { fn to_string(&self) -> String { todo!() } } fn main() { let a = TestStruct { a: 5, b: "hello".to_string(), }; println!("Our Test Struct as JSON: {}", a.to_string()); } ``` -------------------------------- ### Rust: Helper function for Connection and Request Source: https://rust-unofficial.github.io/patterns/print.html Use a wrapping helper function to simplify creating a `Connection` and `Request`, reducing boilerplate code in examples. This is useful when `no_run` is not strictly required but compile-time checks are desired. ```rust struct Connection { name: String, stream: TcpStream, } impl Connection { /// Sends a request over the connection. /// /// # Example /// ``` /// # fn call_send(connection: Connection, request: Request) { /// let response = connection.send_request(request); /// assert!(response.is_ok()); /// # } /// ``` fn send_request(&self, request: Request) -> Result { // ... } } ``` -------------------------------- ### Derive Macro for Deserialize Source: https://rust-unofficial.github.io/patterns/functional/optics.html Example of using the `#[derive(Deserialize)]` macro to automatically implement the `Deserialize` trait for a struct. ```APIDOC ## `#[derive(Deserialize)]` Macro ### Description The `#[derive(Deserialize)]` macro automatically generates an implementation of the `Deserialize` trait for a struct or enum, simplifying the process of making types deserializable. ### Method `#[derive(Deserialize)]` ### Endpoint N/A (Attribute macro) ### Parameters Applied to a struct or enum definition. ### Request Body N/A ### Response N/A ### Code Example ```rust use serde::Deserialize; #[derive(Deserialize)] struct IdRecord { name: String, customer_id: String, } ``` ``` -------------------------------- ### Compile-Time Error Example Source: https://rust-unofficial.github.io/patterns/functional/generics-type-classes.html Attempting to call a protocol-specific method (e.g., `mount_point()`) on a request type that does not support it (e.g., `FileDownloadRequest`) results in a compile-time error. ```Rust fn main() { let mut socket = crate::bootp::listen()?; while let Some(request) = socket.next_request()? { match request.mount_point().as_ref() { "/secure" => socket.send("Access denied"), _ => {} // continue on... } // Rest of the code here } } ``` -------------------------------- ### Rust Struct with Serde Derive and Visitor Generation Source: https://rust-unofficial.github.io/patterns/print.html Example of a Rust struct using a `Serde` derive macro for automatic trait implementation and a macro to generate an associated visitor type. ```rust #[derive(Default, Serde)] // the "Serde" derive creates the trait impl block struct TestStruct { a: usize, b: String, } // user writes this macro to generate an associated visitor type generate_visitor!(TestStruct); ``` -------------------------------- ### Mutex Guard Implementation in Rust Source: https://rust-unofficial.github.io/patterns/patterns/behavioural/RAII.html This example demonstrates a simplified Mutex guard, showcasing RAII for resource management. It ensures that a mutex is unlocked when the guard goes out of scope. Access to the guarded data is mediated through the guard. ```rust use std::ops::Deref; struct Foo {} struct Mutex { // We keep a reference to our data: T here. //.. } struct MutexGuard<'a, T: 'a> { data: &'a T, //.. } // Locking the mutex is explicit. impl Mutex { fn lock(&self) -> MutexGuard { // Lock the underlying OS mutex. //.. // MutexGuard keeps a reference to self MutexGuard { data: self, //.. } } } // Destructor for unlocking the mutex. impl<'a, T> Drop for MutexGuard<'a, T> { fn drop(&mut self) { // Unlock the underlying OS mutex. //.. } } // Implementing Deref means we can treat MutexGuard like a pointer to T. impl<'a, T> Deref for MutexGuard<'a, T> { type Target = T; fn deref(&self) -> &T { self.data } } fn baz(x: Mutex) { let xx = x.lock(); xx.foo(); // foo is a method on Foo. // The borrow checker ensures we can't store a reference to the underlying // Foo which will outlive the guard xx. // x is unlocked when we exit this function and xx's destructor is executed. } ``` -------------------------------- ### Concrete Folder Implementation: Renamer Source: https://rust-unofficial.github.io/patterns/patterns/creational/fold.html An example implementation of the `Folder` trait that renames all `Name` nodes to 'foo'. It utilizes default implementations for other node types. ```rust use fold::*; use ast::*; struct Renamer; impl Folder for Renamer { fn fold_name(&mut self, n: Box) -> Box { Box::new(Name { value: "foo".to_owned() }) } } ``` -------------------------------- ### Implement Custom Display for String using Newtype Source: https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html Use a Newtype to create a custom `Display` implementation for `String`, for example, to mask sensitive data like passwords. This example demonstrates overriding the `Display` trait for a `String` wrapper. ```Rust use std::fmt::Display; // Create Newtype Password to override the Display trait for String struct Password(String); impl Display for Password { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "****************") } } fn main() { let unsecured_password: String = "ThisIsMyPassword".to_string(); let secured_password: Password = Password(unsecured_password.clone()); println!("unsecured_password: {unsecured_password}"); println!("secured_password: {secured_password}"); } ``` -------------------------------- ### Rust Serde API Overview Source: https://rust-unofficial.github.io/patterns/print.html Explains the core components and their interactions within the Serde API. ```APIDOC ## Serde API Concepts ### Description The Serde API in Rust is designed for efficient and generic serialization and deserialization of data structures. It achieves this through a combination of traits and a visitor pattern. ### Key Components 1. **`Deserialize` Trait**: Implemented by types that can be deserialized from a data format. This is often generated via a derive macro. 2. **`Deserializer` Trait**: Handles the specifics of parsing a data format. It drives the deserialization process by calling methods on a `Visitor`. 3. **`Visitor` Trait**: Defines how to construct a data structure from a generic data model. Each data structure implements a `Visitor` to specify how it should be built. ### Workflow - A `Deserializer` is created for a specific data format (e.g., JSON). - A `Visitor` is created, tailored to the target data structure. - The `Deserializer` traverses the data, calling appropriate `Visitor` methods (e.g., `visit_bool`, `visit_u64`, `visit_str`). - The `Visitor` reconstructs the target data structure based on the data encountered. ### Example Data Structure Transformation For a simple structure, the expected visitor pattern might involve: 1. Beginning a map. 2. Visiting string keys. 3. Visiting map values (which could be other maps, lists, or primitives). 4. Ending maps and lists. 5. Storing the reconstructed data into the target structure's fields. ``` -------------------------------- ### Deriving and Using the Default Trait in Rust Source: https://rust-unofficial.github.io/patterns/idioms/default.html Demonstrates how to automatically derive the `Default` trait for a struct where all fields implement `Default`. Shows how to create a default instance and partially initialize it. ```rust use std::{path::PathBuf, time::Duration}; // note that we can simply auto-derive Default here. #[derive(Default, Debug, PartialEq)] struct MyConfiguration { // Option defaults to None output: Option, // Vecs default to empty vector search_path: Vec, // Duration defaults to zero time timeout: Duration, // bool defaults to false check: bool, } impl MyConfiguration { // add setters here } fn main() { // construct a new instance with default values let mut conf = MyConfiguration::default(); // do something with conf here conf.check = true; println!("conf = {conf:#?}"); // partial initialization with default values, creates the same instance let conf1 = MyConfiguration { check: true, ..Default::default() }; assert_eq!(conf, conf1); } ``` -------------------------------- ### Struct with Derive Deserialize Source: https://rust-unofficial.github.io/patterns/functional/optics.html Example of deriving the Deserialize trait for a struct using a macro. This automatically generates the necessary implementation for deserializing the struct from data. ```rust use serde::Deserialize; #[derive(Deserialize)] struct IdRecord { name: String, customer_id: String, } ``` -------------------------------- ### Define AST Nodes for Folding Source: https://rust-unofficial.github.io/patterns/patterns/creational/fold.html Defines the abstract syntax tree (AST) nodes used in the folding example. These structures represent the data that will be processed. ```rust mod ast { pub enum Stmt { Expr(Box), Let(Box, Box), } pub struct Name { value: String, } pub enum Expr { IntLit(i64), Add(Box, Box), Sub(Box, Box), } } ``` -------------------------------- ### Command Pattern Implementation in Rust Source: https://rust-unofficial.github.io/patterns/patterns/behavioural/command.html This snippet implements the Command pattern using a trait for migration operations. It includes structs for `CreateTable` and `AddField`, a `Schema` struct to manage commands, and a `main` function to demonstrate their usage. Use this for scenarios requiring deferred execution or undoable operations. ```rust __ pub trait Migration { fn execute(&self) -> &str; fn rollback(&self) -> &str; } pub struct CreateTable; impl Migration for CreateTable { fn execute(&self) -> &str { "create table" } fn rollback(&self) -> &str { "drop table" } } pub struct AddField; impl Migration for AddField { fn execute(&self) -> &str { "add field" } fn rollback(&self) -> &str { "remove field" } } struct Schema { commands: Vec>, } impl Schema { fn new() -> Self { Self { commands: vec![] } } fn add_migration(&mut self, cmd: Box) { self.commands.push(cmd); } fn execute(&self) -> Vec<&str> { self.commands.iter().map(|cmd| cmd.execute()).collect() } fn rollback(&self) -> Vec<&str> { self.commands .iter() .rev() // reverse iterator's direction .map(|cmd| cmd.rollback()) .collect() } } fn main() { let mut schema = Schema::new(); let cmd = Box::new(CreateTable); schema.add_migration(cmd); let cmd = Box::new(AddField); schema.add_migration(cmd); assert_eq!(vec!["create table", "add field"], schema.execute()); assert_eq!(vec!["remove field", "drop table"], schema.rollback()); } ``` -------------------------------- ### Declarative Summation with Fold in Rust Source: https://rust-unofficial.github.io/patterns/functional/paradigms.html Employ this declarative method using `fold` for a more functional style of summing numbers. It composes addition functions with a range, starting from an initial value. ```rust #![allow(unused)] fn main() { println!("{}", (1..11).fold(0, |a, b| a + b)); } ``` -------------------------------- ### Chain Iterator with Option in Rust Source: https://rust-unofficial.github.io/patterns/idioms/option-iter.html Use `.chain()` to append an `Option`'s element to an existing iterator. Note that `turing.iter()` is used to get an iterator over the `Option`'s content. ```Rust #![allow(unused)] fn main() { let turing = Some("Turing"); let logicians = vec!["Curry", "Kleene", "Markov"]; for logician in logicians.iter().chain(turing.iter()) { println!("{logician} is a logician"); } } ``` -------------------------------- ### Manual Facade Method Implementation in Rust Source: https://rust-unofficial.github.io/patterns/anti_patterns/deref.html An alternative to Deref polymorphism, this shows how to manually implement facade methods to delegate calls to a composed struct. This approach is more explicit and less surprising than using Deref. ```rust impl Bar { fn m(&self) { self.f.m() } } ``` -------------------------------- ### Rust: Build with Deny Warnings Flag Source: https://rust-unofficial.github.io/patterns/print.html Use the RUSTFLAGS environment variable to set linting behavior at build time. This approach decouples build settings from the code itself. ```bash RUSTFLAGS="-D warnings" cargo build ``` -------------------------------- ### Using &str function with sentence splitting Source: https://rust-unofficial.github.io/patterns/idioms/coercion-arguments.html This example demonstrates using the `three_vowels` function (declared with `&str`) to check words within a sentence. It highlights the flexibility of `&str` over `&String` for such operations. ```Rust fn three_vowels(word: &str) -> bool { let mut vowel_count = 0; for c in word.chars() { match c { 'a' | 'e' | 'i' | 'o' | 'u' => { vowel_count += 1; if vowel_count >= 3 { return true; } } _ => vowel_count = 0, } } false } fn main() { let sentence_string = "Once upon a time, there was a friendly curious crab named Ferris".to_string(); for word in sentence_string.split(' ') { if three_vowels(word) { println!("{word} has three consecutive vowels!"); } } } ``` -------------------------------- ### Implementing `Deref` for Smart Pointer Behavior Source: https://rust-unofficial.github.io/patterns/print.html The `Deref` trait allows types to be treated like smart pointers, enabling implicit dereferencing. This example shows `Deref` implementation for a `Vec` to a slice `[T]`. ```rust use std::ops::Deref; struct Vec { data: RawVec, //.. } impl Deref for Vec { type Target = [T]; fn deref(&self) -> &[T] { //.. } } ``` -------------------------------- ### Serde API Overview Source: https://rust-unofficial.github.io/patterns/functional/optics.html Conceptual overview of the Serde API structure with generic types for serialization and deserialization. ```APIDOC ## Serde API Concepts ### Normal Form ```rust case class Serde[T, F] { serialize: T, F -> String deserialize: String, F -> Result[T, Error] } ``` ### Prism Concept The `Visitor` type allows each data structure to define its own parsing logic, bridging the Serde API with specific data formats. ### Enhanced Normal Form ```rust case class Serde[T] { serialize: F -> String deserialize F, String -> Result[T, Error] } case class VisitorForT { build: F, String -> Result[T, Error] decompose: F, T -> String } case class SerdeFormat[T, V] { toString: T, V -> String fromString: V, String -> Result[T, Error] } ``` ### Serde API Implementation Details 1. **`Deserialize` / `Serialize` Traits**: Each type to be serialized implements these traits, equivalent to the `Serde` class. 2. **`Visitor` Trait**: A type implementing the `Visitor` trait handles the logic to construct or deconstruct data between the data type and the Serde data model format. This is often generated by a derive macro. 3. **`Deserializer` Trait**: This trait handles format-specific details, driven by the `Visitor`. ``` -------------------------------- ### Dynamic Dispatch with Mutable References in Rust Source: https://rust-unofficial.github.io/patterns/idioms/on-stack-dyn-dispatch.html Demonstrates dynamic dispatch using mutable references for I/O operations, allowing either standard input or a file to be read. Requires Rust 1.79.0 or later for automatic lifetime extension. ```Rust use std::io; use std::fs; fn main() -> Result<(), Box> { let arg = "-"; // We need to describe the type to get dynamic dispatch. let readable: &mut dyn io::Read = if arg == "-" { &mut io::stdin() } else { &mut fs::File::open(arg)? }; // Read from `readable` here. Ok(()) } ``` -------------------------------- ### ToString for Cow Source: https://rust-unofficial.github.io/patterns/print.html Illustrates the specialization of the `ToString` method for `Cow` when the type parameter is `str`. ```Rust impl<'_> ToString for Cow<'_, str> ``` -------------------------------- ### Visitor Pattern AST and Interpreter Implementation in Rust Source: https://rust-unofficial.github.io/patterns/patterns/behavioural/visitor.html Defines the abstract syntax tree (AST) for a simple expression language and an Interpreter visitor to evaluate these expressions. Requires the ast and visit modules. ```Rust // The data we will visit mod ast { pub enum Stmt { Expr(Expr), Let(Name, Expr), } pub struct Name { value: String, } pub enum Expr { IntLit(i64), Add(Box, Box), Sub(Box, Box), } } // The abstract visitor mod visit { use ast::*; pub trait Visitor { fn visit_name(&mut self, n: &Name) -> T; fn visit_stmt(&mut self, s: &Stmt) -> T; fn visit_expr(&mut self, e: &Expr) -> T; } } use ast::*; use visit::*; // An example concrete implementation - walks the AST interpreting it as code. struct Interpreter; impl Visitor for Interpreter { fn visit_name(&mut self, n: &Name) -> i64 { panic!() } fn visit_stmt(&mut self, s: &Stmt) -> i64 { match *s { Stmt::Expr(ref e) => self.visit_expr(e), Stmt::Let(..) => unimplemented!(), } } fn visit_expr(&mut self, e: &Expr) -> i64 { match *e { Expr::IntLit(n) => n, Expr::Add(ref lhs, ref rhs) => self.visit_expr(lhs) + self.visit_expr(rhs), Expr::Sub(ref lhs, ref rhs) => self.visit_expr(lhs) - self.visit_expr(rhs), } } } ``` -------------------------------- ### Concatenate Strings with format! Source: https://rust-unofficial.github.io/patterns/idioms/concat-format.html Use `format!` for convenient string building, especially with mixed literal and non-literal strings. For maximum efficiency, consider `push` operations on a pre-allocated mutable string. ```Rust #![allow(unused)] fn main() { fn say_hello(name: &str) -> String { // We could construct the result string manually. // let mut result = "Hello ".to_owned(); // result.push_str(name); // result.push('!'); // result // But using format! is better. format!("Hello {name}!") } } ``` -------------------------------- ### Illustrating Borrow Checker Issue with Large Struct Source: https://rust-unofficial.github.io/patterns/print.html This example demonstrates a scenario where a large struct causes borrow checker conflicts due to simultaneous mutable and immutable borrow attempts. It highlights the problem that struct decomposition aims to solve. ```rust struct Database { connection_string: String, timeout: u32, pool_size: u32, } fn print_database(database: &Database) { println!("Connection string: {}", database.connection_string); println!("Timeout: {}", database.timeout); println!("Pool size: {}", database.pool_size); } fn main() { let mut db = Database { connection_string: "initial string".to_string(), timeout: 30, pool_size: 100, }; let connection_string = &mut db.connection_string; print_database(&db); *connection_string = "new string".to_string(); } ``` ```rust let connection_string = &mut db.connection_string; ------------------------- mutable borrow occurs here print_database(&db); ^^^ immutable borrow occurs here *connection_string = "new string".to_string(); ------------------ mutable borrow later used here ``` -------------------------------- ### Rust Unsafe myset_store Function Source: https://rust-unofficial.github.io/patterns/patterns/ffi/wrappers.html An example of an unsafe function that stores a value in a set while potentially iterating over it. This function demonstrates how mutable access to the set can violate Rust's aliasing rules if an iterator is active, leading to undefined behavior. ```rust pub mod unsafe_module { // other module content pub fn myset_store(myset: *mut MySetWrapper, key: datum, value: datum) -> libc::c_int { // DO NOT USE THIS CODE. IT IS UNSAFE TO DEMONSTRATE A PROBLEM. let myset: &mut MySet = unsafe { // SAFETY: whoops, UB occurs in here! &mut (*myset).myset }; /* ...check and cast key and value data... */ match myset.store(casted_key, casted_value) { Ok(_) => 0, Err(e) => e.into(), } } } ``` -------------------------------- ### Rust Concordance Structure and SerDe Implementation Source: https://rust-unofficial.github.io/patterns/print.html Provides a basic Rust structure for Concordance and an outline for its serialization and deserialization methods. Note that the implementation details are marked as 'todo!()'. ```rust #![allow(unused)] fn main() { use std::collections::HashMap; struct Concordance { keys: HashMap, value_table: Vec<(usize, usize)>, } struct ConcordanceSerde {} impl ConcordanceSerde { fn serialize(value: Concordance) -> String { todo!() } // invalid concordances are empty fn deserialize(value: String) -> Concordance { todo!() } } } ``` -------------------------------- ### DBM API Definition in C Source: https://rust-unofficial.github.io/patterns/patterns/ffi/export.html This C code defines the DBM (Database Manager) API, which serves as an example of an object-based API for file-based databases. It includes types for opaque database handles and data elements, along with functions for managing the database. ```c struct DBM; typedef struct { void *dptr, size_t dsize } datum; int dbm_clearerr(DBM *); void dbm_close(DBM *); int dbm_delete(DBM *, datum); int dbm_error(DBM *); datum dbm_fetch(DBM *, datum); datum dbm_firstkey(DBM *); datum dbm_nextkey(DBM *); DBM *dbm_open(const char *, int, mode_t); int dbm_store(DBM *, datum, datum, int); ``` -------------------------------- ### Using `#[non_exhaustive]` for Extensible Structs and Enums in Rust Source: https://rust-unofficial.github.io/patterns/idioms/priv-extend.html Demonstrates how to apply `#[non_exhaustive]` to structs and enums to allow adding new variants or fields in the future without breaking existing code. It shows how to handle these constructs in match statements using `..` and wildcard patterns. ```rust #![allow(unused)] fn main() { mod a { // Public struct. #[non_exhaustive] pub struct S { pub foo: i32, } #[non_exhaustive] pub enum AdmitMoreVariants { VariantA, VariantB, #[non_exhaustive] VariantC { a: String, }, } } fn print_matched_variants(s: a::S) { // Because S is `#[non_exhaustive]`, it cannot be named here and // we must use `..` in the pattern. let a::S { foo: _, .. } = s; let some_enum = a::AdmitMoreVariants::VariantA; match some_enum { a::AdmitMoreVariants::VariantA => println!("it's an A"), a::AdmitMoreVariants::VariantB => println!("it's a b"), // .. required because this variant is non-exhaustive as well a::AdmitMoreVariants::VariantC { a, .. } => println!("it's a c"), // The wildcard match is required because more variants may be // added in the future _ => println!("it's a new variant"), } } } ```