Rust获取数组中长度最短的字符串或最小数值
题目0:给定一个数组[T; n],求最小值,其中T为i32类型
fn get_min(vals: &[i32]) -> Option<&i32> {
vals.iter().min_by_key(|x| x.abs())
}
fn main() {
let a: [i32; 5] = [-3_i32, 0, 1, 5, -10];
println!("min: {:?}", a.iter().min());
println!("min value: {:?}", *a.iter().min_by_key(|x| x.abs()).unwrap());
println!("min by: {:?}", *a.iter().min_by(|x, y| x.cmp(y)).unwrap());
println!("min value from function: {:?}", get_min(&a));
}
注:
该例子中的数组是定长数组[T; n]
题目1:给定一个Vec动态数组,求最小值
fn get_min2(vals: &Vec<i32>) -> Option<&i32> {
vals.iter().min_by_key(|x| x.abs())
}
fn main() {
let a: Vec<i32> = vec![-3_i32, 0, 1, 5, -10];
println!("min: {:?}", a.iter().min());
println!("min value: {:?}", *a.iter().min_by_key(|x| x.abs()).unwrap());
println!("min by: {:?}", *a.iter().min_by(|x, y| x.cmp(y)).unwrap());
println!("min value from function: {:?}", get_min2(&a));
}
注:
若数据类型是u32时,需要多加注意,有些方法是不适用的。
fn main() {
//let b: Vec<i32> = vec![3,12,4];
let mut b: Vec<u32> = Vec::new();
b.push(3);
b.push(12);
b.push(4);
println!("MIN BY KEY: {:?}", b.iter().min_by_key(|x| x.abs()));
}
# cargo run
Compiling rust_failure v0.1.0 (/root/RustProjects/rust_failure)
error[E0599]: no method named `abs` found for reference `&&u32` in the current scope
--> src/main.rs:48:60
|
48 | println!("MIN BY KEY: {:?}", b.iter().min_by_key(|x| x.abs()));
| ^^^ method not found in `&&u32`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0599`.
error: could not compile `rust_failure`.
题目2:给定一个Vec<&str>动态数组,求最短字符串
fn get_shortest(names: Vec<&str>) -> Option<&str>{
let name = names.iter().fold(names[0], |acc, &item| {
if item.len() > acc.len() {
acc
} else {
item
}
});
return Some(name);
}
fn main() {
println!("{:?}", get_shortest(vec!["Ukr", "KX", "MKSDSD"]));
}
注:
使用fold
消费器,可以有效简化代码。