Max By Key And Min By Key Selection
Pick extremes from iterators with max_by_key and min_by_key, which return the last maximum and first minimum and collapse to None on empty input.
Code
fn main() {
let services = [
("api", 120u32),
("web", 95),
("jobs", 410),
("db", 260),
];
// max_by_key:按键取最大,并列时返回最后一个
let busiest = services.iter().max_by_key(|(_, latency)| latency);
println!("busiest: {busiest:?}");
// min_by_key:取最小的那个,并列时返回第一个
let quietest = services.iter().min_by_key(|(_, latency)| latency);
println!("quietest: {quietest:?}");
// 从空序列取极值收敛为 Option
let empty: [(&str, u32); 0] = [];
println!("empty max: {:?}", empty.iter().max_by_key(|(_, l)| l));
}How it works
Max By Key And Min By Key Selection reduces to the function main.
Putting it to use
Running the file prints labeled results such as busiest:, quietest:, empty max: — each operation’s effect is visible in the output.
Core lines
let quietest = services.iter().min_by_key(|(_, latency)| latency);
let busiest = services.iter().max_by_key(|(_, latency)| latency);
Interactive Tools for This Topic
FAQ
- What does Max By Key And Min By Key Selection print when run?
- The script runs standalone; its 3 labeled outputs include `busiest:`, `quietest:`, `empty max:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.