当前位置:网站首页>Based article 】 【 learn with Rust | Rust function and process control, rounding
Based article 】 【 learn with Rust | Rust function and process control, rounding
2022-07-29 11:50:00 【Guang Longyu】
文章目录
前言
在之前的学习中,你已经见过RustOne of the most important function in the——main,He is a program's entrance function.In this section we will explain in detailRustPart of the function and process control,Studying the current content,Your code will be more rich.
一、函数
函数在Rust中是非常普遍的.With the function to encapsulate some process,Would improve code reuse rate.Rust In the code function and variable names to use snake case 规范风格.在 snake case 中,All the letters are lower case and use the underline separate words.这个与python是一致的,如果你经常用python,So you will be particularly familiar with,The following is in accordance with snake case 风格的字符串
get_user_name
set_user_name
1. 定义函数
我们在Rust 中通过输入 fn Followed by the function name and a pair of parentheses to define the function.Braces tell the compiler where is the beginning of the function body and end.A no arguments function structure is as follows
fn function_name(){
}



What bread in the curly braces,我们称之为——作用域.
2. 函数参数
We can define a function with parameter,Parameter is a special variable,是函数签名的一部分.
注意:Function signatures this keyword is especially important to,See him you have to think that he is to define the function of the code
从定义上来讲,参数分为形参和实参.Parameter is defined function,The parameters of the function signature learn inside,It is only the logo at this time,没有实际意义,Examples of parameter as shown below
注意:在函数签名中,必须 Declare the type of each parameter.When defining multiple parameters,使用逗号分隔.
fn function_name(name: &str, age: u8) {
print!("{} 已经 {} 岁了", name, age);
}
Here to a function defines two functions,一个是name,是字符串类型的,一个是age是8个bit整数型的.Here is the parameter,We can use inside the function expressions and statements of,But alone this parameter is meaningless,Send it only has practical value to,You can be understood as a placeholder labels.
There are arguments,The actual value argument is passed to a function,It has the practical significance.And it is passed to the parameters of.The following is the argument passed to the parameter example
function_name("张三",24);
这是一个Rust语句,Call the write abovefunction_name函数,并且传入两个参数,Zhang SAN is a string type,Is an integer24,代表年龄.这就是实参,When we were in the call of the incoming parameter is the argument.
3. 语句和表达式
The body of the function consists of a series of statements and the end of an optional expression.因为 Rust Is a language based on expression,This is a need to understand、The important distinction between the is different from other languages.
Statement is to perform some action but not return value instruction.Expressions to calculate and generate a value.
下面给出一个例子,We learn from what is a statement,什么是表达式.
fn main() {
let y = {
let x = 3;
x + 1
};
println!("y的值是: {y}");
}
一般来说,在Rust中,Statement by a semicolon at the end of,And no semicolon at the end of expression,并且需要返回一个值.在上面的代码中

The expression with curly braces wrapped up,That the expression is a block of code,Inside the code block is a statement,最后x+1作为返回值,This we then speak.
4. Function with return
Function can be invoked to its code return value.We are not on the return value is named,But in the arrow(->)The type of statement after it.在 Rust 中,The return value of a function is equivalent to the final value of the expression function body.That is why the above code blocks the final is a expression.The following is to define a function with a return value,
fn get_age(name: &str) -> u8 {
return 18;
}
使用 return Keywords and specify a value,Can return from the function in advance;But the majority of the last expression of function of implicit return.So the above code can also wrote
fn get_age(name: &str) -> u8 {
18
}
We can also use the return value of a variable to receive the function
let age = get_age();
二、流程控制
According to the condition is true to decide whether to execute some code,And according to the condition is true to repeat the ability of a piece of code is an essential part of most programming languages.Rust The most common type of code used to control the flow of execution structure is if 表达式和循环.
1. if条件跳转
if Expression is allowed according to the different code branch of conditional execution.You provide a condition and say 如果条件满足,运行这段代码;如果条件不满足,Don't run this code.
以下是使用ifTo determine the condition of a small case
fn main() {
let number = 3;
if number < 5 {
println!("条件为true");
} else {
println!("条件为false");
}
}
这里定义了一个变量number,并且赋值为3,后面的ifIs the condition of a select statement.if后面,Before the curly braces is the condition,
Conditions must be an expression,并且返回True或者False
Followed by two blocks of code,一个是条件为true执行的代码块,一个是条件为false执行的代码块.
Now run the effect
此时我们将number改成7,再次执行

判断条件必须是true或者false的表达式,一下是错误用法
fn main() {
let number = 3;
if number {
println!("number是3");
}
}
The usage is wrong,Rust没有和CThe language that the0即true的规则.
else if处理多个条件
可以将 else if 表达式与 if 和 else Combine multiple conditions to implement.The following is an example of dealing with multiple conditions,Judge whether a number can be2,3,4整除
fn main() {
let number = 6;
if number % 4 == 0 {
println!("number 被 4 整除");
} else if number % 3 == 0 {
println!("number 被 3 整除");
} else if number % 2 == 0 {
println!("number 被 2 整除");
} else {
println!("number 不能被 4, 3, 或 2 整除");
}
}

将if表达式赋值给变量
可以用if语句返回值,And as an expression to use,
fn main() {
let condition = true;
let number = if condition {
5 } else {
6 };
println!("number的值是: {number}");
}
如上,如果condition 是true的话,number就是5,否则就是6,要注意的是,The returned value must be the same type of,因为RustType must be sure,以下就是错误的用法
fn main() {
let condition = true;
let number = if condition {
5 } else {
"six" };
println!("number的值是: {number}");
}
2.loop循环
Many times to perform the same piece of code is very commonly used,Rust Provides a variety of 循环(loops).A loop execution code until the end of the loop body and then back to continue.
Rust 有三种循环:loop、while 和 for.
loop 关键字告诉 Rust Again and again to perform a piece of code until you explicitly demanded an end to.以下是一个使用loop循环的例子,The output of the constantlyagain!
fn main() {
loop {
println!("again!");
}
}
运行如下
使用ctrl+c以退出循环
We don't have to write out condition here,通常我们会使用break来退出循环
fn main() {
let mut x = 0;
loop {
x += 1;
if x == 10 {
break;
}
println!("x 的值是: {}", x);
}
}
At the same time also can exit and return value
fn main() {
let mut x = 0;
let result_value = loop {
x += 1;
if x == 10 {
break x;
}
println!("x 的值是: {}", x);
};
println!("result_value 的值是: {}", result_value);
}
输出结果如下
循环标签
Loop tag is used to eliminate the ambiguity between multiple cycle.如果存在嵌套循环,break 和 continue Applied to the innermost circle at this time.You can choose on a cycle to specify a 循环标签(loop label),Then put the label with break 或 continue 一起使用,Make these keywords is applied to a tagged cycle rather than the innermost circle.
fn main() {
let mut count = 0;
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up;
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}");
}
The outer loop has a label counting_up,它将从 0 数到 2.There is no label of inner loop from 10 Count down to 9.The first do not specify a label break Will only be out of the inner loop.break 'counting_up; Statement would pull out of the outer loop.
3. while条件循环
whileLoop and other programming languages,Only meet the condition cycle,以下是while循环的一个例子,
fn main() {
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
}
println!("LIFTOFF!!!");
}
The above code implements a logic,如果number不等于0Executes the contents of the code block,也就是number减一,Until run to qualify.
This kind of structure to eliminate a lot of use loop、if、else 和 break Necessary for nested,这样更加清晰.When the condition is true perform,否则退出循环.
4. for循环
forCycle we mainly use to traverse a collection,在Java中,我们通常称为for循环是while的一个语法糖,实际上while能做的,for也能做,以下是一个whileImplementation of array again
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("值是: {}", a[index]);
index += 1;
}
}
这里,The code of the elements in the array to count.它从索引 0 开始,And then the cycle until meet the array index of the last(这时,index < 5 不再为真).并输出该元素.
如果我们用forCycle to traverse is like this
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("值是: {element}");
}
}
It looks simple a lot,But pay attention to the key wordsin后面必须是一个集合,So you can also write
fn main() {
for element in [10, 20, 30, 40, 50] {
println!("值是: {element}");
}
}
In addition can also outputrange序列,The following is the output1到10
fn main() {
for element in (1..10) {
println!("值是: {element}");
}
}
总结
以上就是本期的所有内容.This part mainly talked about the two,分别是rustThe function and process control.Functions mainly introduces the definition and function of ginseng and no,形参和实参,还把rustStatements and expressions of the way for a moment.Introduces the commonly used several kinds of process control program flow control of grammar,循环,条件等.
如果你也对Rust感兴趣,可以点个关注,与我一起探讨、学习Rust.
边栏推荐
- Basic. Blocking
- DAY 27 daily SQL clock 】 【 丨 within a specified period of time all order products [difficult simple]
- MySql启动、连接sqlog、主从复制、双机热备(开机时)
- 593. 有效的正方形 : 简单几何运用题
- Recursion - Eight Queens Problem
- 力扣sql刷题(四)
- Std:: vector copy, append, nested access
- Deep understanding of c # delegate into the fast lanes
- js 数组常用API
- After connect and SQL join in on conditions and where
猜你喜欢

ECCV 2022 | SSP: 自支持匹配的小样本任务新思想

QML(一):自定义圆角按钮的处理

Why should kubernetes be used in development environments

Similarities and differences of QWidget, qdialog and qmainwindow

How to use grep to find pattern matching across multiple lines
![[image detection] Research on cumulative weighted edge detection method based on gray image, with matlab code](/img/c1/f962f1c1d9f75732157d49a5d1d0d6.png)
[image detection] Research on cumulative weighted edge detection method based on gray image, with matlab code

Basic Concepts of Kubernetes

报表查询字段集sql摘记

GDB使用详解

【年中总结】创业3年,越来越穷,还是坚持架构平台
随机推荐
Package Delivery(贪心)
使用anyio替代asyncio
Proficient in audio and video development can really do whatever you want
MFC学习备忘
迁徙数据平台简单介绍
北京大学公开课重磅来袭!欢迎走进「AI for Science」课堂
[image detection] Research on cumulative weighted edge detection method based on gray image, with matlab code
共建共享数字世界的根:阿里云打造全面的云原生开源生态
WeChat red envelope test case
Insights into the development of the enterprise live broadcast industry in 2022
QML(一):自定义圆角按钮的处理
Kubernetes基本概念
【每日SQL打卡】DAY 26丨广告效果【难度简单】
Paddlelite compilation and code running through the disk
c语言:来实现一个小程序n子棋(已五子棋为例)
游戏合作伙伴专题:BreederDAO 与《王国联盟》结成联盟
Deep understanding of c # nullable types
IPv6 Foundation
Mall mall based on flask --- user module
解决idea在debug模式下变得非常慢的问题