rust - 哪一个在 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
}
解决方案
在这种特殊情况下,最惯用的解决方案是
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 中无处不在。您可以在此处阅读所有允许使用模式的地方。
推荐阅读
- python - 如何使用美丽的汤刮标签属性列表?
- python - 比较两个字符串并在Python中提取变量数据的值
- naming - 是否有变量命名约定
- r - 更改 R 中的 scattermapbox 符号
- c# - 如何组合两个不同类型的列表?
- git - 仅当该仓库中存在未在管道定义中配置的 git 提交时才触发 Jenkins 构建
- google-chrome - 如何在 WebdriverIO 测试中避免 chrome 外部对话框
- python - ValueError:检查目标时出错:预期的 dense_22 具有 3 个维度,但得到的数组形状为 (1600, 2)
- lua - 如何使用 Lua 建立与“ttgo t call esp32 sim800L”的互联网连接
- android - 正常扫描二维码后,停止运行,无法显示扫描内容: