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
Fromfor infallible, obvious conversions. - Use
TryFromorFromStrfor validation and fallible parsing. - Use
Fromfor lossless numeric widening andTryFromfor narrowing or signedness changes. - Choose explicit overflow behavior with
checked_*,saturating_*,wrapping_*, oroverflowing_*. - Use
as_*for borrowed or scalar views,to_*for created values, andinto_*for consuming conversions. - Name field-like accessors
id(),name(), orstatus()and predicatesis_*,has_*, orcan_*. - Borrow accessors unless returning a small
Copyvalue; ownership policy owns return choices.
Avoid
- Do not use
Fromfor validation, failure, surprising allocation, or lossy meaning. - Do not use unchecked
asfor narrowing or float-to-integer conversion. - Do not use approximate floats with
==or sort NaN-capable floats withouttotal_cmp. - Do not name allocating methods
as_*. - Do not use
get_*for simple observation or generate every possible accessor. - Do not implement
Derefmerely 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.