NonZero Types Reject Zero At Construction
Turn zero-rejection into a type with NonZeroU32 and NonZeroUsize: construction returns Option, division by the value cannot panic, and the compiler knows it.
Code
use std::num::{NonZeroU32, NonZeroUsize};
// 分页参数:每页大小绝不能是 0,让类型替我们把关
#[derive(Debug)]
struct PageRequest {
page: u32,
page_size: NonZeroU32,
}
fn parse_request(page: u32, raw_size: u32) -> Result<PageRequest, String> {
// NonZeroU32::new 返回 Option:0 在入口就被拒绝
let page_size = NonZeroU32::new(raw_size)
.ok_or_else(|| format!("page_size must be positive, got {raw_size}"))?;
Ok(PageRequest { page, page_size })
}
fn main() {
println!("{:?}", parse_request(1, 25));
println!("{:?}", parse_request(2, 0));
// NonZeroUsize 直接当除数:除法不可能 panic
let capacity = NonZeroUsize::new(4).unwrap();
let buckets: Vec<u32> = vec![10, 20, 30, 40];
let per_bucket = buckets.len() / capacity;
println!("{buckets:?} / {capacity} -> {} per bucket", per_bucket);
}How it works
NonZero Types Reject Zero At Construction is built around the functions parse_request and main.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
What to watch for
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
The main signature reads fn parse_request(page: u32, raw_size: u32) -> Result<PageRequest, String>
The demo flow inside main is parse_request — run the file to see it end to end.
Key statements
fn parse_request(page: u32, raw_size: u32) -> Result<PageRequest, String> {
// NonZeroU32::new 返回 Option:0 在入口就被拒绝
let page_size = NonZeroU32::new(raw_size)
.ok_or_else(|| format!("page_size must be positive, got {raw_size}"))?;
Ok(PageRequest { page, page_size })
}
let capacity = NonZeroUsize::new(4).unwrap();
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What happens when a call fails?
- Through the type system: failures are `Result` variants the caller must consume.
- How do you run NonZero Types Reject Zero At Construction?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.