Study Rust Bible analysis - Rust learn-4 (functions, comments, control flow)
function
Functions are useful for code encapsulation and reuse
declare function
By using the fn keyword we can declare a function
fn test() {
println!("test")
}
Call functions
Function names are parenthesized like in other languages
fn main() {
test()
}
fn test() {
println!("test")
}
expression
In Rust we can set a function expression for a variable to set the value of the variable
let x = {
5+9
};
is equivalent to writing:
let x = add();
fn add(){
return 5+9
}
note
All programmers strive to make their code easy to understand, but sometimes it is necessary to provide additional explanations, which are comments
single line comment
//
multiline comment
/**/
Documentation comments (important)
///
Rust can detect whether there is a problem with the code in your documentation comments, which can not only ensure the correctness of the code but also keep the documentation up-to-date
control flow
Decide whether to execute some code based on whether a condition is true
if-else decision
fn main() {
let n = 5;
if n > 6 {
println!("1")
} else if n == 6 {
println!("2")
}else {
println!("3")
}
}
loop cycle
The loop keyword tells Rust to execute a piece of code over and over until you explicitly ask it to stop
loop{
//...
}
out of loop
loop{
//...
break;
}
jump out and carry the return value
loop{
//...
break 返回值;
}
Jump out of the specified loop
We may encounter multiple loops superimposed, which is very effective when the inner loop ends and needs to jump out of the outer loop, and this is also the magic of the Rust life cycle
'out:loop{
'mid:loop{
'inner:loop{
break 'out;
}
}
}
while loop
fn main() {
let n = 5;
while n-1>0{
//....
}
}
for loop
The for in Rust is more like python because it is for-in
let eles = [1,2,3]
for ele in eles{
//...
}
for i in (0..10){
//...
}