Num Structs
Numeric wrapper types ใน Rust สำหรับ special numeric behaviors, optimizations, และ error handling
1. NonZero Types
Section titled “1. NonZero Types”NonZeroXxx types guarantee ค่าไม่เป็น zero ให้ memory optimization กับ Option ด้วย niche optimization
Using NonZero
Section titled “Using NonZero”use std::num::{NonZeroU32, NonZeroI64, NonZeroUsize};
fn main() { // Create NonZero - returns Option let nz = NonZeroU32::new(42).expect("must be non-zero"); println!("NonZeroU32: {}", nz);
// Returns None for zero let zero = NonZeroU32::new(0); println!("From zero: {:?}", zero); // None
// Get inner value let value: u32 = nz.get(); println!("Inner value: {}", value);
// Memory optimization! println!("\n=== Size comparison ==="); println!("u32: {} bytes", std::mem::size_of::<u32>()); println!("Option<u32>: {} bytes", std::mem::size_of::<Option<u32>>()); println!("Option<NonZeroU32>: {} bytes", std::mem::size_of::<Option<NonZeroU32>>()); // Same size due to niche optimization!
// Signed NonZero let signed = NonZeroI64::new(-42).unwrap(); println!("\nNonZeroI64: {}", signed);
// Checked arithmetic let a = NonZeroU32::new(10).unwrap(); if let Some(sum) = a.checked_add(5) { println!("10 + 5 = {}", sum); }
// Saturating (won't become zero) let sat = nz.saturating_add(u32::MAX); println!("saturating_add(MAX): {}", sat);}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google