Conversion method takes a receiver its name prefix does not imply
ID |
rust.maintainability.wrong_self_convention |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Api Design |
Language |
Rust |
Description
Reports a method whose name prefix promises one receiver and whose signature declares another: an into_* method that borrows instead of consuming, a from_* method that takes a receiver at all instead of being an associated function, or an as_* method that consumes self instead of borrowing it.
Rationale
These prefixes are a contract about cost and ownership that every Rust reader relies on: into_ means the value is consumed, as_ means a cheap borrowed view, from_ means a constructor called on the type. A method that breaks the contract is used incorrectly at the call site - a caller who expects as_ to borrow discovers the move only from a compiler error, and one who expects into_ to consume keeps a copy that was never needed.
The following code illustrates the pattern detected by this rule:
pub struct Record {
id: u64,
label: String,
}
pub struct Summary {
id: u64,
}
impl Record {
// FLAGGED: Conversion method takes a receiver its name prefix does not imply
pub fn into_summary(&self) -> Summary {
Summary { id: self.id }
}
}