简体   繁体   English

rust 中哪一个更惯用?

[英]Which one is more Idiomatic in rust?

Which is more idiomatic rust in this case,在这种情况下,哪个更惯用 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
}

or或者

//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
}

In this particular case, the most idiomatic solution would be在这种特殊情况下,最惯用的解决方案是

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

But if I had to choose between the two functions you wrote, I'd pick the second one.但是,如果我必须在您编写的两个函数之间进行选择,我会选择第二个。

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

for loops accept a pattern . for循环接受一个模式 list.iter() is an iterator over items with the type &i32 , which is pattern-matched against &item , so item is destructured into a i32 . list.iter()是类型&i32的项目的迭代器,它与&item进行模式匹配,因此item解构i32 This has the same effect as dereferencing it.这与取消引用它具有相同的效果。

Pattern matching is pervasive in Rust.模式匹配在 Rust 中无处不在。 You can read about all the places where patterns are allowed here .您可以在此处阅读所有允许使用模式的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM