Tshem tawm mus ntev qhov tsis haum thaum ua kev hloov pauv ntawm cov lej thiab cov lej ntab ntab. Txij li thaum Rust compiler siv LLVM ua tus backend, hom kev hloov pauv tau ua los ntawm LLVM cov lus qhia nruab nrab ntawm cov lej xws li fptoui ua, uas muaj ib qho tseem ceeb feature - undefined tus cwj pwm yog hais tias qhov tshwm sim tus nqi tsis haum rau hom phiaj. Piv txwv li, thaum hloov tus nqi ntab 300 nrog hom f32 rau integer type u8, qhov tshwm sim tsis tuaj yeem pom thiab yuav txawv ntawm ntau lub tshuab. Qhov teeb meem yog qhov no feature tshwm nyob rau hauv code uas tsis cim raws li "tsis zoo".
Raws li Rust 1.45, tus cwj pwm ntawm hom loj overflow yog nruj me ntsis tswj, thiab "raws li" hloov dua siab tshiab ua hauj lwm checks rau overflow thiab quab yuam tus nqi hloov mus rau qhov siab tshaj plaws los yog yam tsawg kawg nkaus tus nqi ntawm lub hom phiaj (piv txwv li saum toj no, tus nqi ntawm 300 yuav hloov mus rau 255). Txhawm rau lov tes taw cov tshev no, ntxiv API hu β{f64, f32}::to_int_uncheckedβ tau muab, ua haujlwm hauv hom tsis zoo.
fn cast(x:f32) -> u8 {
xws u8
}
fn main() {
cia too_big = 300.0;
cia too_small = -100.0;
cia nan = f32::NAN;
ua x:f32 = 1.0;
cia y: u8 = unsafe {x.to_int_unchecked() };
Lub rustc compiler tau ntxiv kev txhawb nqa rau overriding ntau lub hom phiaj platform nta siv tus chij "target-feature", piv txwv li, "-C target-feature=+avx2,+fma". Cov chij tshiab kuj tau ntxiv:
"force-unwind-tables" los tsim cov rooj sib tham hu xov tooj, tsis hais txog kev sib tsoo lub tswv yim; "embed-bitcode" los tswj seb LLVM bitcode puas suav nrog hauv rlibs tsim. Tus chij "embed-bitcode" tau qhib los ntawm lub neej ntawd hauv Cargo los txhim kho lub sijhawm tsim thiab siv qhov chaw disk.