std-method
slice::sort_by
Supply a consistent comparator when natural ordering is not suitable. For floating-point numbers, total_cmp gives a total ordering including NaN and signed zero. Expected stdout (not executed): [-1.0, 2.0, 3.5] Common mistake: Unwrapping partial_cmp on floating-point data without considering NaN.
Formal Syntax & Structure
rust syntaxrust
slice.sort_by(|a, b| ordering)Working Example
Example Snippetrust
fn main() { let mut values = [3.5_f64, -1.0, 2.0]; values.sort_by(|a, b| a.total_cmp(b)); println!("{values:?}");}