G.CNS.02 宜使用标准库中的预定义常量
【级别】 建议
【描述】
Rust 中提供了一些特殊常量的定义(例如std::f32::consts),其精确度通常会比开发者自行定义的高, 所以若考虑数值精确度时,宜使用标准库预定义的特殊常量。
【反例】
Rust
let min: i8 = -128;
let max: u16 = 65535;
// 不符合
let x = 3.14_f64; let y = 1_f64 / x;
【正例】
Rust
let min: i8 = i8::MIN;
let max: u16 = u16::MAX;
let x = std::f64::consts::PI;
let y = std::f64::consts::FRAC 1 PI;
let inf = f32::INFINITY;
let neg_inf = f32::NEG_INFINITY;