Hint Functions
Compiler hints และ optimization
unreachable_unchecked
Section titled “unreachable_unchecked”fn main() { // unreachable_unchecked - UNSAFE optimization hint
fn process(n: u32) -> u32 { match n { 0 => 0, 1 => 1, _ => n * 2, } }
// Safe version fn fast_divide(a: u32, b: u32) -> u32 { if b == 0 { panic!("division by zero"); } a / b }
// Unsafe version - only when 100% certain unsafe fn fast_divide_unchecked(a: u32, b: u32) -> u32 { if b == 0 { std::hint::unreachable_unchecked(); } a / b }
println!("Safe: {}", fast_divide(10, 2));
unsafe { println!("Unsafe: {}", fast_divide_unchecked(10, 2)); }
// When to use: // - Performance critical code // - When you can PROVE the branch is never taken // - After profiling shows it helps
// DANGER: UB if reached! println!("Done safely!");}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google