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.

RustForm Validation

Code

rustsnippet
26 lines
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 own match.

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

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.