当前位置:网站首页>Trust finds the maximum value in the array
Trust finds the maximum value in the array
2022-07-23 17:47:00 【pilaf1990】
Make a little progress every day .
rust The procedure for finding the maximum value of elements in the array is as follows :
fn main() {
let vec = vec![1,2,56,13,68];
let largest1 = largest1(&vec);
let largest2 = largest2(&vec);
println!("largest1 is:{}", largest1);
println!("largest2 is:{}", largest2);
}
fn largest1(list:&[i32])->i32{
// Why is the type obtained by subscript i32, And by for The element type obtained by the loop is &i32
let mut largest = list[0]; // amount to let mut largest = (*list.index(0));
for &item in list {
if largest < item {
largest = item;
}
}
largest
}
fn largest2(list:&[i32])->i32{
let mut largest = list[0];
for item in list {
if largest < *item {
largest = *item;
}
}
largest
}
We go through vec! Macro call
let vec = vec![1,2,56,13,68];
An array is defined vec,vec The type is Vec<i32>.
By defining largest1 and largest2 Function to find the largest in the array i32 Type values , And back to (rust The value of the last expression in the function is the return value , Note that it is not a statement , That is, there is no semicolon end . It can also be used. return Display the specified return value , This and scala Its grammar is a bit like ). The functions of the two functions are the same , Just to learn two kinds of quotation and dereference for Usage of loop .
Two largest The input parameter types of functions are &[i32], It means that we just reference the array , Don't take ownership of it .
Let's have a look at it first Clion( Other development tools such as VSCode It should be the same ) The type information of the variable inferred from is as follows :
There are two questions to consider :
1. Why? list yes &[i32] type , and list[0] What we get is i32 type , No &i32 type ?
2. Why? for The elements of the loop can be used &item, It can also be used. item, What's the difference ?
answer :
1.rust Said on the official website container[index] is actually syntactic sugar for *container.index(index), That is, for container types , Access the elements of the container by subscript , In fact, that is * Containers .index( Subscript serial number ) The grammar sugar of . and Vec Yes, it is container, It has achieved Index trait:
let mut largest = list[0]; amount to let mut largest = (*list.index(0));
list.index(0) The return is &i32 type , It becomes i32 type ( similar C Add an asterisk before the pointer variable in the language to get the variable pointed by the pointer ).
2.rust Medium for Circulation is actually a grammatical sugar (java China, too , In fact, elements are accessed through iterators ), It is said on the official website :for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over a common practice within Rust, which is to loop over anything that implements IntoIterator until the iterator returned by .into_iter() returns None (or the loop body uses break).
about &[i32] Type of list,for The elements in the loop are &i32, So no matter for After the cycle is &item still item, They are taken as a whole , The type is &i32 type , That is, if &item yes &i32, that item Namely i32 type , visit list When using elements in item That's all right. ; If for There is only item, that item Namely &i32 type , Want to visit for The element value in the loop must be dereferenced , That is, through *item Way to obtain list The value of the element in .
Reference material :
1.https://stackoverflow.com/questions/71981790/why-does-indexing-a-vec-return-a-value-instead-of-a-reference-as-promised-by-the
2.https://doc.rust-lang.org/std/ops/trait.Index.html
3.https://doc.rust-lang.org/std/keyword.for.html
边栏推荐
- @Will multiple bean instances be created by multiple method calls of bean annotations
- Food safety chocolate is also true or false? How much do you know about it
- MySQL7种JOIN(图)
- Makefile common functions notdir, wildcard, patsubst
- MySQL主从同步延迟解决方案
- Repository XXX does not have a rease file "suggested collection"
- In depth understanding of USB communication protocol
- MongoDB分组取每组中一条数据
- vim 笔记
- Interviewer: how to use redis to realize distributed locks?
猜你喜欢

【作业】研一(互联网新技术作业)

New opportunities for cultural tourism in the era of digital intelligence? China Mobile Migu creates "the first island in the yuan universe"

xlinx pcie xvc

MySQL大量写入问题优化方案 MySQL参数调优

ride the wind and waves! Digital transformation in the era of financial technology

nVisual综合布线管理软件与网管软件的区别

Aike AI frontier promotion (7.23)

rust求数组中最大值

训练和测试的loss不下降,并且精度超低

深入理解机械系统的模态与振动
随机推荐
From Markov chain to GPT, Li Hang, director of ByteDance AI Lab, detailed the past and present lives of language models
服务器环境搭建
PDO操作
isEmpty 和 isBlank 的用法区别,至少一半的人答不上来...
Food safety | attention to smoking food, do you know this knowledge
工業物聯網中的時序數據
Time series data in industrial Internet of things
乘风破浪!金融科技时代下的数字化转型之路
Food safety eating preserved eggs will lead poisoning? Don't worry about eating after knowing these points
Geometric parametric reconstruction
Leetcode skimming: dynamic programming 05 (different paths II)
[introduction series of redis] data types and related commands of redis
Emgu cv3+c # image processing (IV): use emgucv to obtain camera and read video
From 5 seconds to 1 second, remember the performance optimization with "very" significant effect once
一加OnePlus 10T的一系列规格在产品发布前被披露
xlinx pcie xvc
Single cell thesis record (part19) -- a comprehensive comparison on cell type composition information for St data
ride the wind and waves! Digital transformation in the era of financial technology
tp&smarty使用日记
MongoDB分组取每组中一条数据