Newtype Pattern for Type Safety
Wrap primitives in newtypes so distinct identifiers and units cannot be mixed, adding validation and methods without runtime cost.
Code
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Meters(f64);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Seconds(f64);
#[derive(Debug)]
enum SpeedError {
ZeroDuration,
}
impl Meters {
fn per(self, duration: Seconds) -> Result<f64, SpeedError> {
if duration.0 <= 0.0 {
return Err(SpeedError::ZeroDuration);
}
Ok(self.0 / duration.0)
}
}
fn main() {
let distance = Meters(100.0);
let duration = Seconds(9.58);
match distance.per(duration) {
Ok(speed) => println!("speed = {speed:.2} m/s"),
Err(error) => eprintln!("invalid: {error:?}"),
}
}How the snippet works
Newtype Pattern for Type Safety reduces to the functions per and main.
Result turns the error into data — visible in the type, handled by the caller. match here is the control flow: arms enumerate the value’s shapes exhaustively.
Watch out for
- The
Resultvalues will not let errors pass silently; each must be matched, unwrapped, or propagated.
Applying it
The main signature reads fn per(self, duration: Seconds) -> Result<f64, SpeedError>
Running the file prints labeled results such as speed = — each operation’s effect is visible in the output.
There are 1 call inside main — per — executed top to bottom.
Statements that matter
return Err(SpeedError::ZeroDuration);
match distance.per(duration) {
Ok(speed) => println!("speed = {speed:.2} m/s"),
Err(error) => eprintln!("invalid: {error:?}"),
}
Ok(self.0 / duration.0)
}
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.
FAQ
- How should callers handle failures?
- No panics — `Result` values carry the failure.
- What does Newtype Pattern for Type Safety print when run?
- The script runs standalone; its 1 labeled outputs include `speed =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.