Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Conversions, Getters, and Method Naming

Rule

Use honest conversion traits and method prefixes: From is infallible, TryFrom and FromStr validate, as_ borrows, to_ creates, into_ consumes, and field-like accessors use bare names.

Why

Conversion and method names communicate failure, ownership, and allocation without requiring callers to inspect implementations.

Do

  • Use From for infallible, obvious conversions.
  • Use TryFrom or FromStr for validation and fallible parsing.
  • Use From for lossless numeric widening and TryFrom for narrowing or signedness changes.
  • Choose explicit overflow behavior with checked_*, saturating_*, wrapping_*, or overflowing_*.
  • Use as_* for borrowed or scalar views, to_* for created values, and into_* for consuming conversions.
  • Name field-like accessors id(), name(), or status() and predicates is_*, has_*, or can_*.
  • Borrow accessors unless returning a small Copy value; ownership policy owns return choices.

Avoid

  • Do not use From for validation, failure, surprising allocation, or lossy meaning.
  • Do not use unchecked as for narrowing or float-to-integer conversion.
  • Do not use approximate floats with == or sort NaN-capable floats without total_cmp.
  • Do not name allocating methods as_*.
  • Do not use get_* for simple observation or generate every possible accessor.
  • Do not implement Deref merely to forward inner methods.

Example

#![allow(unused)]
fn main() {
impl ProjectName {
    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn to_slug(&self) -> String {
        self.0.to_ascii_lowercase().replace(' ', "-")
    }

    pub fn into_string(self) -> String {
        self.0
    }
}

impl std::str::FromStr for ProjectName {
    type Err = ProjectNameError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::try_new(value)
    }
}
}

Exceptions

  • Use get_* for keyed lookup, cache retrieval, or fallible computed access.
  • Return named owned snapshots when borrowing would expose unnecessary lifetimes.