### Borrowing Builder Usage Examples Source: https://rust-lang.github.io/api-guidelines/print.html Illustrates how to use a borrowing builder for both concise one-liner commands and more complex, conditional configurations. ```Rust #![allow(unused)] fn main() { // One-liners Command::new("/bin/cat").arg("file.txt").spawn(); // Complex configuration let mut cmd = Command::new("/bin/ls"); if size_sorted { cmd.arg("-S"); } cmd.arg("."); cmd.spawn(); } ``` -------------------------------- ### Poor Example of `clone()` Usage Source: https://rust-lang.github.io/api-guidelines/documentation.html This example demonstrates a mechanical call to `clone()` without illustrating its practical purpose or benefit. ```rust fn main() { let hello = "hello"; hello.clone(); } ``` -------------------------------- ### Example with Error Handling using ? Source: https://rust-lang.github.io/api-guidelines/print.html A common structure for fallible example code using the `?` operator for error propagation. Lines starting with `#` are for testing but not displayed. ```Rust # use std::error::Error; # # fn main() -> Result<(), Box> { # your; # example?; # code; # # Ok(()) # } ``` -------------------------------- ### Cargo.toml with Optional Dependencies and Features Source: https://rust-lang.github.io/api-guidelines/naming.html Example of `Cargo.toml` defining optional dependencies and a feature that enables the standard library. ```toml [package] name = "x" version = "0.1.0" [features] std = ["serde/std"] [dependencies] serde = { version = "1.0", optional = true } ``` -------------------------------- ### Using `?` for Fallible Operations in Examples Source: https://rust-lang.github.io/api-guidelines/documentation.html This pattern is recommended for fallible example code, using `?` for error propagation. Lines starting with `#` are for testing and not displayed to users. ```rust /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` ``` -------------------------------- ### Linking to Parent or Child Modules Source: https://rust-lang.github.io/api-guidelines/documentation.html These markdown examples illustrate how to create links to documentation in parent or child modules using relative paths. ```markdown [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html ``` -------------------------------- ### Documenting Panics Due to Caller's Implementation Source: https://rust-lang.github.io/api-guidelines/documentation.html This example shows how to document panics that occur due to the caller's implementation, such as when `T`'s `Display` implementation panics. ```rust #![allow(unused)] fn main() { /// # Panics /// /// This function panics if `T`'s implementation of `Display` panics. pub fn print(t: T) { println!("{}", t.to_string()); } } ``` -------------------------------- ### Documenting Panic Conditions for `Vec::insert` Source: https://rust-lang.github.io/api-guidelines/documentation.html This example illustrates documenting panic conditions for a method, specifically for `Vec::insert` which panics if the index is out of bounds. ```rust /// Inserts an element at position `index` within the vector, shifting all /// elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. ``` -------------------------------- ### Public Dependency Stability Example Source: https://rust-lang.github.io/api-guidelines/necessities.html This example demonstrates a public function that uses a type from another crate. For this crate to be stable, 'other_crate' must also be stable. ```rust #![allow(unused)] fn main() { pub fn do_my_thing(arg: other_crate::TheirThing) { /* ... */ } } ``` -------------------------------- ### Macro Input Syntax: Keywords and Punctuation Source: https://rust-lang.github.io/api-guidelines/print.html Illustrates preferred macro input syntax by mirroring existing Rust syntax. This example shows how to use keywords like `struct` and punctuation like semicolons to make macro input more familiar and cohesive with the rest of the code. ```Rust #![allow(unused)] fn main() { // Prefer this... bitflags! { struct S: u32 { /* ... */ } } // ...over no keyword... bitflags! { S: u32 { /* ... */ } } // ...or some ad-hoc word. bitflags! { flags S: u32 { /* ... */ } } } ``` ```Rust #![allow(unused)] fn main() { // Ordinary constants use semicolons. const A: u32 = 0b000001; const B: u32 = 0b000010; // So prefer this... bitflags! { struct S: u32 { const C = 0b000100; const D = 0b001000; } } // ...over this. bitflags! { struct S: u32 { const E = 0b010000, const F = 0b100000, } } } ``` -------------------------------- ### Conversion Constructor with `from_` Prefix Source: https://rust-lang.github.io/api-guidelines/predictability.html Demonstrates conversion constructors that create a new type from an existing value of a different type, using `std::io::Error::from_raw_os_error` as an example. ```rust std::io::Error::from_raw_os_error ``` -------------------------------- ### Private Dependency Stability Example Source: https://rust-lang.github.io/api-guidelines/necessities.html This example shows a struct with a private implementation detail that uses a type from another crate. This setup is generally safe for stability even if 'other_crate' is unstable, as 'ErrorImpl' is private. ```rust #![allow(unused)] fn main() { pub struct Error { private: ErrorImpl, } enum ErrorImpl { Io(io::Error), // Should be okay even if other_crate isn't // stable, because ErrorImpl is private. Dep(other_crate::Error), } // Oh no! This puts other_crate into the public API // of the current crate. impl From for Error { fn from(err: other_crate::Error) -> Self { Error { private: ErrorImpl::Dep(err) } } } } ``` -------------------------------- ### Using Booleans for Widget Configuration (Discouraged) Source: https://rust-lang.github.io/api-guidelines/print.html Avoid using generic booleans for configuration parameters as their meaning can be ambiguous without context. This example shows creating a `Widget` with `true` and `false` values. ```Rust #![allow(unused)] fn main() { let w = Widget::new(true, false) } ``` -------------------------------- ### Documenting Error Conditions for `std::io::Read::read` Source: https://rust-lang.github.io/api-guidelines/documentation.html This example shows how to document potential error conditions for a trait method, indicating that errors will be returned if I/O issues occur and that no bytes will be read in such cases. ```rust /// Pull some bytes from this source into the specified buffer, returning /// how many bytes were read. /// /// ... lots more info ... /// /// # Errors /// /// If this function encounters any form of I/O or other error, an error /// variant will be returned. If an error is returned then it must be /// guaranteed that no bytes were read. ``` -------------------------------- ### Rust Code with Conditional Compilation for Features Source: https://rust-lang.github.io/api-guidelines/naming.html Example of conditional compilation in `lib.rs` for a `std` feature. ```rust #![no_std] #[cfg(feature = "std")] extern crate std; ``` -------------------------------- ### Rust Command Builder (Borrowed Self) Source: https://rust-lang.github.io/api-guidelines/type-safety.html Example of a builder pattern where configuration methods take and return a mutable borrow of self. This allows the final `spawn` method to take the builder by shared reference. ```rust #![allow(unused)] fn main() { // NOTE: the actual Command API does not use owned Strings; // this is a simplified version. pub struct Command { program: String, args: Vec, cwd: Option, // etc } impl Command { pub fn new(program: String) -> Command { Command { program: program, args: Vec::new(), cwd: None, } } /// Add an argument to pass to the program. pub fn arg(&mut self, arg: String) -> &mut Command { self.args.push(arg); self } /// Add multiple arguments to pass to the program. pub fn args(&mut self, args: &[String]) -> &mut Command { self.args.extend_from_slice(args); self } /// Set the working directory for the child process. pub fn current_dir(&mut self, dir: String) -> &mut Command { self.cwd = Some(dir); self } /// Executes the command as a child process, which is returned. pub fn spawn(&self) -> io::Result { /* ... */ } } } ``` -------------------------------- ### Secondary Constructor with Suffix Source: https://rust-lang.github.io/api-guidelines/predictability.html Shows the convention of using `_with_foo` suffixes for secondary constructors when multiple construction options exist, using `Mmap::open_with_offset` as an example. ```rust Mmap::open_with_offset ``` -------------------------------- ### Unsafe Conversion Constructor Source: https://rust-lang.github.io/api-guidelines/predictability.html Provides an example of an unsafe conversion constructor, `Box::from_raw`, which differs from `From` trait implementations. ```rust Box::from_raw ``` -------------------------------- ### Example: `Vec::as_mut_slice` Method Signature Source: https://rust-lang.github.io/api-guidelines/naming.html This snippet shows the signature for a method that returns a mutable slice. The `mut` qualifier in the name indicates that the returned slice is mutable. ```rust #![allow(unused)] fn main() { // Return type is a mut slice. fn as_mut_slice(&mut self) -> &mut [T]; } ``` -------------------------------- ### Macro Item Placement: Module vs. Function Scope Source: https://rust-lang.github.io/api-guidelines/print.html Highlights the importance of ensuring macros work correctly in different scopes, including module and function levels. This example contrasts a working macro invocation with one that fails due to scope-related issues. ```Rust #![allow(unused)] fn main() { #[cfg(test)] mod tests { test_your_macro_in_a!(module); #[test] fn anywhere() { test_your_macro_in_a!(function); } } } ``` ```Rust #![allow(unused)] fn main() { macro_rules! broken { ($m:ident :: $t:ident) => { pub struct $t; pub mod $m { pub use super::$t; } } } broken!(m::T); // okay, expands to T and m::T fn g() { broken!(m::U); // fails to compile, super::U refers to the containing module not g } } ``` -------------------------------- ### Type Enforcement Example (Ascii Wrapper) Source: https://rust-lang.github.io/api-guidelines/print.html Illustrates using a newtype pattern to enforce input validity at compile time. The `Ascii` wrapper ensures that the highest bit of a `u8` is zero. ```Rust #![allow(unused)] fn main() { fn foo(a: Ascii) { /* ... */ } } ``` ```Rust #![allow(unused)] fn main() { fn foo(a: u8) { /* ... */ } } ``` -------------------------------- ### Using Custom Types for Widget Configuration Source: https://rust-lang.github.io/api-guidelines/print.html Prefer explicit custom types like `Small` and `Round` over booleans for configuration parameters to improve clarity and extensibility. This example shows creating a `Widget` with specific size and shape enums. ```Rust #![allow(unused)] fn main() { let w = Widget::new(Small, Round) } ``` -------------------------------- ### Rust Task Builder (Owned Self) Source: https://rust-lang.github.io/api-guidelines/type-safety.html Example of a consuming builder pattern where configuration methods take and return an owned self. This is necessary when ownership transfer is required for constructing the final type. ```rust #![allow(unused)] fn main() { impl TaskBuilder { /// Name the task-to-be. pub fn named(mut self, name: String) -> TaskBuilder { self.name = Some(name); self } /// Redirect task-local stdout. pub fn stdout(mut self, stdout: Box) -> TaskBuilder { self.stdout = Some(stdout); self } /// Creates and executes a new child task. pub fn spawn(self, f: F) where F: FnOnce() + Send { /* ... */ } } } ``` -------------------------------- ### Documenting Safety Invariants for `std::ptr::read` Source: https://rust-lang.github.io/api-guidelines/documentation.html This example details the safety requirements for an unsafe function, explaining the invariants the caller must uphold, such as ensuring the pointer is aligned and managing memory usage to prevent issues with non-`Copy` types. ```rust /// Reads the value from `src` without moving it. This leaves the /// memory in `src` unchanged. /// /// # Safety /// /// Beyond accepting a raw pointer, this is unsafe because it semantically /// moves the value out of `src` without preventing further usage of `src`. /// If `T` is not `Copy`, then care must be taken to ensure that the value at /// `src` is not used before the data is overwritten again (e.g. with `write`, /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use /// because it will attempt to drop the value previously at `*src`. /// /// The pointer must be aligned; use `read_unaligned` if that is not the case. ``` -------------------------------- ### Illustrating Breaking Changes with Derivable Trait Bounds Source: https://rust-lang.github.io/api-guidelines/future-proofing.html This example demonstrates how adding a derivable trait like PartialOrd as an explicit bound on a generic struct can introduce a breaking change, unlike simply deriving it. ```rust #![allow(unused)] fn main() { // Non-breaking change: #[derive(Clone, Debug, PartialEq, PartialOrd)] struct Good { /* ... */ } // Breaking change: #[derive(Clone, Debug, PartialEq, PartialOrd)] struct Bad { /* ... */ } } ``` -------------------------------- ### Using Custom Types for Clarity Source: https://rust-lang.github.io/api-guidelines/type-safety.html Prefer custom types (enums, structs) over generic types like `bool` or `Option` to convey meaning and enforce invariants. This example shows `Small` and `Round` being more descriptive than `true` and `false`. ```Rust #![allow(unused)] fn main() { let w = Widget::new(Small, Round) } ``` ```Rust #![allow(unused)] fn main() { let w = Widget::new(true, false) } ``` -------------------------------- ### Using a Basic Constructor Source: https://rust-lang.github.io/api-guidelines/predictability.html Shows how to use the `new` constructor to create an instance of a type, assuming the type is fully imported. ```rust #![allow(unused)] fn main() { use example::Example; // Construct a new Example. let ex = Example::new(); } ``` -------------------------------- ### Using Consuming Task Builder Source: https://rust-lang.github.io/api-guidelines/type-safety.html Illustrates how to use a consuming builder, showing both one-liner and complex configuration scenarios. Complex configurations require re-assignment to retain ownership. ```rust #![allow(unused)] fn main() { // One-liners TaskBuilder::new("my_task").spawn(|| { /* ... */ }); // Complex configuration let mut task = TaskBuilder::new(); task = task.named("my_task_2"); // must re-assign to retain ownership if reroute { task = task.stdout(mywriter); } task.spawn(|| { /* ... */ }); } ``` -------------------------------- ### Basic Constructor Convention Source: https://rust-lang.github.io/api-guidelines/predictability.html Demonstrates the basic convention of a `new` method with no arguments for type instantiation. ```rust #![allow(unused)] fn main() { impl Example { pub fn new() -> Example { /* ... */ } } } ``` -------------------------------- ### Using Borrowed Command Builder Source: https://rust-lang.github.io/api-guidelines/type-safety.html Demonstrates convenient usage of the borrowed builder pattern for both simple one-liners and complex configurations. ```rust #![allow(unused)] fn main() { // One-liners Command::new("/bin/cat").arg("file.txt").spawn(); // Complex configuration let mut cmd = Command::new("/bin/ls"); if size_sorted { cmd.arg("-S"); } cmd.arg("."); cmd.spawn(); } ``` -------------------------------- ### README.md License Section Source: https://rust-lang.github.io/api-guidelines/necessities.html Include a section in your README.md file to clearly state the dual licensing of your project. ```markdown ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. ``` -------------------------------- ### Constructor with Arguments Source: https://rust-lang.github.io/api-guidelines/predictability.html Illustrates that constructors can accept arguments, such as `Box::new` which takes the value to be placed in the `Box`. ```rust Box::new ``` -------------------------------- ### Rust Getter Naming for Specific Cases Source: https://rust-lang.github.io/api-guidelines/naming.html The 'get' naming is reserved for single, obvious accessors like `Cell::get`. For methods with runtime validation, consider adding `_unchecked` variants. ```rust fn get(&self, index: K) -> Option<&V>; fn get_mut(&mut self, index: K) -> Option<&mut V>; unsafe fn get_unchecked(&self, index: K) -> &V; unsafe fn get_unchecked_mut(&mut self, index: K) -> &mut V; ``` -------------------------------- ### Cargo.toml for Dual Licensing Source: https://rust-lang.github.io/api-guidelines/necessities.html Configure your Cargo.toml file to specify the dual MIT/Apache-2.0 license for your crate. ```toml [package] name = "..." version = "..." authors = ["..."] license = "MIT OR Apache-2.0" ``` -------------------------------- ### Conversion Constructor with Additional Arguments Source: https://rust-lang.github.io/api-guidelines/predictability.html Shows a conversion constructor, `u64::from_str_radix`, that accepts additional arguments to disambiguate the source data. ```rust u64::from_str_radix ``` -------------------------------- ### Distinguishing Similar Types with Newtypes Source: https://rust-lang.github.io/api-guidelines/type-safety.html Use newtypes to create distinct types from underlying primitives, preventing accidental mixing of values with different interpretations. This example shows how `Miles` and `Kilometers` can be defined and converted. ```Rust #![allow(unused)] fn main() { struct Miles(pub f64); struct Kilometers(pub f64); impl Miles { fn to_kilometers(self) -> Kilometers { /* ... */ } } impl Kilometers { fn to_miles(self) -> Miles { /* ... */ } } } ``` -------------------------------- ### Linking to Another Type's Documentation Source: https://rust-lang.github.io/api-guidelines/documentation.html This markdown syntax shows how to link to the documentation of a different type, specifically `Deserialize`, using its relative HTML path. ```markdown [`Deserialize`]: trait.Deserialize.html ``` -------------------------------- ### Type-Safe Flag Sets with `bitflags` Source: https://rust-lang.github.io/api-guidelines/type-safety.html The `bitflags` crate provides a type-safe way to represent sets of flags, offering a Rust equivalent to C-style bit manipulation for flags. This example defines and uses a `Flags` struct. ```Rust use bitflags::bitflags; bitflags! { struct Flags: u32 { const FLAG_A = 0b00000001; const FLAG_B = 0b00000010; const FLAG_C = 0b00000100; } } fn f(settings: Flags) { if settings.contains(Flags::FLAG_A) { println!("doing thing A"); } if settings.contains(Flags::FLAG_B) { println!("doing thing B"); } if settings.contains(Flags::FLAG_C) { println!("doing thing C"); } } fn main() { f(Flags::FLAG_A | Flags::FLAG_C); } ``` -------------------------------- ### Domain-Specific Constructor Names Source: https://rust-lang.github.io/api-guidelines/predictability.html Highlights that I/O resource types often use domain-specific names for constructors, like `File::open`. ```rust File::open ``` -------------------------------- ### Generic function with precise type constraints Source: https://rust-lang.github.io/api-guidelines/flexibility.html This example demonstrates a generic function that consumes and produces elements of exactly the same type `T`, ensuring type safety and preventing invocation with parameters of different types that merely implement the same trait. ```rust #![allow(unused)] fn main() { fn binary(x: T, y: T) -> T } ``` -------------------------------- ### Conversion Constructor for Bitwise Data Source: https://rust-lang.github.io/api-guidelines/predictability.html Illustrates conversion constructors like `u64::from_be` used when the source data is a bag of bits and the constructor name clarifies the encoding. ```rust u64::from_be ``` -------------------------------- ### Box::into_raw Function Definition Source: https://rust-lang.github.io/api-guidelines/predictability.html Illustrates the correct definition of `Box::into_raw` as a free function to avoid method resolution ambiguity. ```rust #![allow(unused)] fn main() { impl Box where T: ?Sized { fn into_raw(b: Box) -> *mut T { /* ... */ } } let boxed_str: Box = /* ... */; let ptr = Box::into_raw(boxed_str); } ``` -------------------------------- ### Prefer familiar keywords in macro input Source: https://rust-lang.github.io/api-guidelines/macros.html When a macro declares a struct, preface the name with `struct` to signal its declaration. ```Rust #![allow(unused)] fn main() { // Prefer this... bitflags! { struct S: u32 { /* ... */ } } // ...over no keyword... bitflags! { S: u32 { /* ... */ } } // ...or some ad-hoc word. bitflags! { flags S: u32 { /* ... */ } } } ``` -------------------------------- ### Ad-hoc Conversion Prefixes Source: https://rust-lang.github.io/api-guidelines/naming.html This table outlines the conventions for ad-hoc conversion methods based on their cost and ownership transfer. Use these prefixes to indicate the nature of the conversion. ```markdown Prefix| Cost| Ownership ---|---|--- `as_`| Free| borrowed -> borrowed `to_`| Expensive| borrowed -> borrowed borrowed -> owned (non-Copy types) owned -> owned (Copy types) `into_`| Variable| owned -> owned (non-Copy types) ``` -------------------------------- ### Opening a file with generic `AsRef` Source: https://rust-lang.github.io/api-guidelines/flexibility.html The `std::fs::File::open` function accepts a generic argument that implements `AsRef`. This allows opening files using various types, such as string literals, `Path` objects, or `OsString`. ```rust std::fs::File::open("f.txt") ``` -------------------------------- ### Follow Rust visibility rules for macro output Source: https://rust-lang.github.io/api-guidelines/macros.html Macros should produce private items by default and public items when `pub` is specified in the macro invocation. ```Rust #![allow(unused)] fn main() { bitflags! { struct PrivateFlags: u8 { const A = 0b0001; const B = 0b0010; } } bitflags! { pub struct PublicFlags: u8 { const C = 0b0100; const D = 0b1000; } } ``` -------------------------------- ### Generic Reader/Writer Implementations Source: https://rust-lang.github.io/api-guidelines/print.html Demonstrates how standard library traits `Read` and `Write` are implemented for mutable references. This allows functions accepting these traits by value to also accept mutable references, which is crucial for new Rust users to understand when dealing with file I/O. ```Rust #![allow(unused)] fn main() { impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ } impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ } } ``` -------------------------------- ### Link to another type Source: https://rust-lang.github.io/api-guidelines/print.html Use markdown link syntax with a file extension to link to other types, typically traits or structs. ```rust __ [`Deserialize`]: trait.Deserialize.html ``` -------------------------------- ### Tagging a Git Commit for Release Source: https://rust-lang.github.io/api-guidelines/documentation.html Use this command to create an annotated Git tag for a specific release version. Annotated tags are preferred for better compatibility with Git commands. ```bash # Tag the current commit GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 git push --tags ``` -------------------------------- ### Linking to a Method within the Same Type Source: https://rust-lang.github.io/api-guidelines/documentation.html This markdown syntax demonstrates how to create an internal link to a method named `serialize_struct` within the current type's documentation. ```markdown [`serialize_struct`]: #method.serialize_struct ``` -------------------------------- ### Link to a parent or child module Source: https://rust-lang.github.io/api-guidelines/print.html Use markdown link syntax with relative paths to link to types in parent or child modules. ```rust __ [`Value`]: ../enum.Value.html [`DeserializeOwned`]: de/trait.DeserializeOwned.html ``` -------------------------------- ### Rust Cargo.toml for Serde optional dependency Source: https://rust-lang.github.io/api-guidelines/interoperability.html Include Serde as an optional dependency in your Cargo.toml file. This allows downstream libraries to opt into Serde implementations by enabling the 'serde' feature. ```toml [dependencies] serde = { version = "1.0", optional = true } ``` -------------------------------- ### Macro Output: Derive Attributes Source: https://rust-lang.github.io/api-guidelines/print.html Demonstrates how macros producing structs or enums can support attributes like `derive` for traits such as `Default` and `Serialize`. This enables the generated items to be used seamlessly with Rust's derive mechanism. ```Rust #![allow(unused)] fn main() { bitflags! { #[derive(Default, Serialize)] struct Flags: u8 { const ControlCenter = 0b001; const Terminal = 0b010; } } } ``` -------------------------------- ### Returning Multiple Values Using Tuples Source: https://rust-lang.github.io/api-guidelines/predictability.html Demonstrates the preferred method for returning multiple values from a function using tuples. ```rust #![allow(unused)] fn main() { fn foo() -> (Bar, Bar) } ``` -------------------------------- ### Macro failing with relative type paths Source: https://rust-lang.github.io/api-guidelines/macros.html Demonstrates a macro that works with primitives and absolute paths but fails when given a relative type path like `S`. ```Rust #![allow(unused)] fn main() { macro_rules! broken { ($m:ident => $t:ty) => { pub mod $m { pub struct Wrapper($t); } } } broken!(a => u8); // okay broken!(b => ::std::marker::PhantomData<()>); // okay struct S; broken!(c => S); // fails to compile } ``` -------------------------------- ### Macro Output: Conditional Attributes Source: https://rust-lang.github.io/api-guidelines/print.html Shows how macros can support adding attributes to individual output items, such as conditional compilation (`cfg`). This allows for more flexible macro usage, like enabling specific features based on the target environment. ```Rust #![allow(unused)] fn main() { bitflags! { struct Flags: u8 { #[cfg(windows)] const ControlCenter = 0b001; #[cfg(unix)] const Terminal = 0b010; } } } ``` -------------------------------- ### Rust Naming Conventions Summary Source: https://rust-lang.github.io/api-guidelines/naming.html This table summarizes the recommended naming conventions for different Rust code items. It covers types, functions, variables, and more. ```markdown Item| Convention ---|--- Crates| unclear Modules| `snake_case` Types| `UpperCamelCase` Traits| `UpperCamelCase` Enum variants| `UpperCamelCase` Functions| `snake_case` Methods| `snake_case` General constructors| `new` or `with_more_details` Conversion constructors| `from_some_other_type` Macros| `snake_case!` Local variables| `snake_case` Statics| `SCREAMING_SNAKE_CASE` Constants| `SCREAMING_SNAKE_CASE` Type parameters| concise `UpperCamelCase`, usually single uppercase letter: `T` Lifetimes| short `lowercase`, usually a single letter: `'a`, `'de`, `'src` Features| unclear but see C-FEATURE ``` -------------------------------- ### Testing Send and Sync Implementations Source: https://rust-lang.github.io/api-guidelines/interoperability.html Use these tests to verify that your custom types correctly implement the Send and Sync traits, ensuring thread safety. ```rust #![allow(unused)] fn main() { #[test] fn test_send() { fn assert_send() {} assert_send::(); } #[test] fn test_sync() { fn assert_sync() {} assert_sync::(); } } ``` -------------------------------- ### Match output syntax for macro input (semicolons) Source: https://rust-lang.github.io/api-guidelines/macros.html If a macro declares a chain of constants, use semicolons to terminate them, mirroring Rust's constant syntax. ```Rust #![allow(unused)] fn main() { // Ordinary constants use semicolons. const A: u32 = 0b000001; const B: u32 = 0b000010; // So prefer this... bitflags! { struct S: u32 { const C = 0b000100; const D = 0b001000; } } // ...over this. bitflags! { struct S: u32 { const E = 0b010000, const F = 0b100000, } } ``` -------------------------------- ### Rust manual Serde implementation with feature gate Source: https://rust-lang.github.io/api-guidelines/interoperability.html Manually implement Serde's Serialize and Deserialize traits for a type, guarded by a Cargo feature. This approach is used when the derive macro is not suitable or desired. ```rust #![allow(unused)] fn main() { pub struct T { /* ... */ } #[cfg(feature = "serde")] impl Serialize for T { /* ... */ } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for T { /* ... */ } } ``` -------------------------------- ### Return Multiple Values Using Tuples or Structs Source: https://rust-lang.github.io/api-guidelines/print.html For functions returning multiple values, prefer using tuples or structs over output parameters. This approach is efficiently compiled and avoids heap allocations. ```rust #![allow(unused)] fn main() { fn foo() -> (Bar, Bar) } ``` ```rust #![allow(unused)] fn main() { fn foo(output: &mut Bar) -> Bar } ``` -------------------------------- ### Rust Cargo.toml for Serde derive with optional dependency Source: https://rust-lang.github.io/api-guidelines/interoperability.html Configure Cargo.toml to include Serde with the 'derive' feature as an optional dependency. This enables the use of Serde's derive macros for automatic serialization and deserialization. ```toml [dependencies] serde = { version = "1.0", optional = true, features = ["derive"] } ``` -------------------------------- ### Link to a method within the same type Source: https://rust-lang.github.io/api-guidelines/print.html Use markdown link syntax with a fragment identifier to link to methods within the same type. ```rust __ [`serialize_struct`]: #method.serialize_struct ``` -------------------------------- ### Ensure macros work in module and function scopes Source: https://rust-lang.github.io/api-guidelines/macros.html Item macros should function correctly both at the module level and within tighter scopes like functions. Test in both. ```Rust #![allow(unused)] fn main() { #[cfg(test)] mod tests { test_your_macro_in_a!(module); #[test] fn anywhere() { test_your_macro_in_a!(function); } } ``` -------------------------------- ### Prefer Method Implementation for Type-Associated Operations Source: https://rust-lang.github.io/api-guidelines/predictability.html Shows the preferred way to define operations associated with a type using methods. ```rust #![allow(unused)] fn main() { impl Foo { pub fn frob(&self, w: widget) { /* ... */ } } } ``` -------------------------------- ### Macro failing in function scope due to scope resolution Source: https://rust-lang.github.io/api-guidelines/macros.html Illustrates a macro that compiles in module scope but fails in function scope due to incorrect super:: resolution. ```Rust #![allow(unused)] fn main() { macro_rules! broken { ($m:ident :: $t:ident) => { pub struct $t; pub mod $m { pub use super::$t; } } } broken!(m::T); // okay, expands to T and m::T fn g() { broken!(m::U); // fails to compile, super::U refers to the containing module not g } } ``` -------------------------------- ### Rust Serde implementation using derive with feature gate Source: https://rust-lang.github.io/api-guidelines/interoperability.html Use Serde's derive macros to automatically implement Serialize and Deserialize for a struct. The derive attribute is conditionally applied based on the 'serde' Cargo feature. ```rust #![allow(unused)] fn main() { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct T { /* ... */ } } ``` -------------------------------- ### Incorrect Box::into_raw Method Definition Source: https://rust-lang.github.io/api-guidelines/predictability.html Demonstrates an incorrect definition of `Box::into_raw` as an inherent method, which can lead to call-site confusion. ```rust #![allow(unused)] fn main() { impl Box where T: ?Sized { // Do not do this. fn into_raw(self) -> *mut T { /* ... */ } } let boxed_str: Box = /* ... */; // This is a method on str accessed through the smart pointer Deref impl. boxed_str.chars() // This is a method on Box...? boxed_str.into_raw() } ``` -------------------------------- ### Prefer taking ownership over borrowing and cloning Source: https://rust-lang.github.io/api-guidelines/flexibility.html When a function requires ownership of an argument, it should take ownership directly. This avoids unnecessary cloning and simplifies the API. ```rust #![allow(unused)] fn main() { // Prefer this: fn foo(b: Bar) { /* use b as owned, directly */ } // Over this: fn foo(b: &Bar) { let b = b.clone(); /* use b as owned after cloning */ } } ``` -------------------------------- ### Common IO Error Constructor Source: https://rust-lang.github.io/api-guidelines/predictability.html The `std::io::Error::new` function is the standard way to construct an IO error. ```rust std::io::Error::new ``` -------------------------------- ### Support attributes for individual macro output items Source: https://rust-lang.github.io/api-guidelines/macros.html Macros producing multiple output items should allow attributes on any item, useful for conditional compilation. ```Rust #![allow(unused)] fn main() { bitflags! { struct Flags: u8 { #[cfg(windows)] const ControlCenter = 0b001; #[cfg(unix)] const Terminal = 0b010; } } ``` -------------------------------- ### Macro Item Visibility: Public vs. Private Source: https://rust-lang.github.io/api-guidelines/print.html Explains the convention for controlling the visibility of items generated by macros. By default, items are private, but they become public when the `pub` keyword is specified, following standard Rust visibility rules. ```Rust #![allow(unused)] fn main() { bitflags! { struct PrivateFlags: u8 { const A = 0b0001; const B = 0b0010; } } bitflags! { pub struct PublicFlags: u8 { const C = 0b0100; const D = 0b1000; } } } ``` -------------------------------- ### Cargo Feature Naming Convention Source: https://rust-lang.github.io/api-guidelines/naming.html Do not include meaningless words in Cargo feature names. Name features directly, like `std` instead of `use-std`. ```toml [features] default = ["std"] std = [] ``` -------------------------------- ### Hiding private implementation details from documentation Source: https://rust-lang.github.io/api-guidelines/print.html Use `#[doc(hidden)]` to prevent implementation details, like private error types or their conversions, from appearing in the public API documentation. ```rust #![allow(unused)] fn main() { // This error type is returned to users. pub struct PublicError { /* ... */ } // This error type is returned by some private helper functions. struct PrivateError { /* ... */ } // Enable use of `?` operator. #[doc(hidden)] impl From for PublicError { fn from(err: PrivateError) -> PublicError { /* ... */ } } } ``` -------------------------------- ### Conditional Compilation for Optional Standard Library Dependency Source: https://rust-lang.github.io/api-guidelines/print.html When a crate has an optional dependency on the Rust standard library, use conditional compilation with `#[cfg(feature = "std")]` and `extern crate std;` in `lib.rs`. ```rust #![allow(unused)] fn main() { // In lib.rs #![no_std] #[cfg(feature = "std")] extern crate std; } ```