面试题答案
一键面试fn sort_with_comparator<T: Ord>(slice: &mut [T], comparator: impl Fn(&T, &T) -> bool) {
slice.sort_by(|a, b| {
if (comparator)(a, b) {
std::cmp::Ordering::Less
} else {
std::cmp::Ordering::Greater
}
});
}
对于闭包的trait bound,这里使用 impl Fn(&T, &T) -> bool
,表示闭包接受两个指向 T
类型的引用,并返回一个布尔值。其中 Fn
是Rust中用于表示可调用闭包的trait,通过这种方式,我们可以确保传入的闭包具有正确的签名,以便在 sort_by
函数中作为比较逻辑使用。