首页 > 解决方案 > 哪一个在 rust 中更惯用?

问题描述

在这种情况下,哪个更惯用的生锈,

//This is a C like a syntax where you can get the value at a location through *.
fn largest_i32(list: &[i32])-> i32{
    let mut largest = list[0];

    for item in list.iter(){
        if *item > largest{
            largest = *item;
        }

    };
    largest
}

或者

//This syntax seems confusing to me, Is rust doing derefrecing iteself.
fn largest_i32(list: &[i32]) -> i32 {
    let mut largest = list[0];

    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }

    largest
}

标签: rust

解决方案


在这种特殊情况下,最惯用的解决方案是

fn largest_i32(list: &[i32]) -> i32 {
    *list.iter().max().unwrap()
}

但是,如果我必须在您编写的两个函数之间进行选择,我会选择第二个。

//This syntax seems confusing to me, Is rust doing derefrecing iteself.

for循环接受一个模式list.iter()是类型为 的项目的迭代器&i32,它与 模式匹配&item,因此item解构i32. 这与取消引用它具有相同的效果。

模式匹配在 Rust 中无处不在。您可以在此处阅读所有允许使用模式的地方。


推荐阅读