当前位置:网站首页>Rust language - Introduction to Xiaobai 05
Rust language - Introduction to Xiaobai 05
2022-07-01 22:45:00 【ImagineMiracle】
1. Rust The variables in the
We learned from the last article that in Rust
Variables defined in are immutable by default . This is a Rust
The features specified by the language to ensure its security and simple concurrency .Rust
The consideration is , When designing a program , Suppose the code just begins to define a value , And the value will never change , But when there is more code , Another part forgets the initial assumption , Changed that value again , Then the previous code may not be executed as expected . that Rust
Will change this situation , When you declare a value without changing it , It really can't be changed ,Rust
The compiler will help you ensure this , This makes the code you build easier to read and reason .
2. Rust The default immutable variable of (immutable)
As usual , We use Cargo
Create a new project , Used to do related experiments . The directory structure after successful creation is as follows .
imaginemiracle:rust_projects$ cargo new variables
imaginemiracle:rust_projects$ cd variables/
imaginemiracle:variables$ tree
.
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
open src/main.rs
Source file , And update the code to the following code .
fn main() {
let val = 27149; // Alarm number of chenyongren ——《 Infernal Affairs 》
println!("The value of val is: {val}");
val = 4927; // Liu Jianming's alarm number ——《 Infernal Affairs 》
println!("The value of val is: {val}");
}
Here we're trying to do something about Rust
Modify the default variable of .OK! Let's run it and see what happens .
imaginemiracle:variables$ cargo run
Compiling variables v0.1.0 (/home/imaginemiracle/Miracle/Code/rust_projects/variables)
error[E0384]: cannot assign twice to immutable variable `val`
--> src/main.rs:7:5
|
3 | let val = 27149; // Alarm number of chenyongren ——《 Infernal Affairs 》
| ---
| |
| first assignment to `val`
| help: consider making this binding mutable: `mut val`
...
7 | val = 4927; // Liu Jianming's alarm number ——《 Infernal Affairs 》
| ^^^^^^^^^^ cannot assign twice to immutable variable
For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` due to previous error
Compiler error :cannot assign twice to immutable variable
Here you can see the compiler telling us “ An immutable variable cannot be assigned twice , Do you want to declare variables as mut Variable variable of ”.
3. Rust Variable variable of (mutable)
Since the default variable is unchangeable , So how to make variables variable ? On this point , If you have read chapter of this series 4
The partner of this article should have been clear . We need to add mut
Keyword to indicate that this variable will be declared as a variable (mutable)
.
Let's put the above src/main.rs
Change to the following code :
fn main() {
let mut val = 27149; // Alarm number of chenyongren ——《 Infernal Affairs 》
println!("The value of val is: {val}");
val = 4927; // Liu Jianming's alarm number ——《 Infernal Affairs 》
println!("The value of val is: {val}");
println!(" I'm sorry , I'm a policeman .");
}
Then run the program again at this time :
imaginemiracle:variables$ cargo run
Compiling variables v0.1.0 (/home/imaginemiracle/Miracle/Code/rust_projects/variables)
Finished dev [unoptimized + debuginfo] target(s) in 0.29s
Running `target/debug/variables`
The value of val is: 27149
The value of val is: 4927
I'm sorry , I'm a policeman .
Oh, We have correctly changed the value of the variable .[ notes ]: stay Rust in , Variable variability , It's up to the developer .
4. Rust The constant (Constants)
Yes C
or C++
Basic friends must know what constants are .Rust
There are constants in (const
), After being declared as a constant , Then the program will not allow you to change the value of this constant , It looks like Rust
The default variable properties in are very similar , Are not allowed to be modified , However, there are some differences between the two .
The differences are as follows :
- The first thing to be clear is ,
const
Modifier constants are not allowedmut
Of , That is, constants must ensure that they are immutable , This point cannot be violated ; - Constant usage
const
Keyword modification , The default immutable variable islet
Keyword modification ; - Use
const
A constant that modifies a declaration must indicate its data type , andlet
You may not display the notes , rely onRust
The compiler automatically recognizes variable types ; - Constants can only be assigned to constant expressions , Instead of just the value calculated at runtime .
Here is an example of a constant declaration :
fn main() {
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
}
The name of the constant is THREE_HOURS_IN_SECONDS
, Its value is assigned 60
( Seconds in a minute ) multiply 60
( Minutes in an hour ) multiply 3
( The number of hours to calculate ).
Another thing to note is :Rust
Constant naming rules in , Use all capitalized words , Underline the space between .
The compiler can evaluate a limited set of operations at compile time , This allows us to choose to write this value in a way that is easier to understand and verify , Instead of setting this constant to a value 10,800
.
The advantage of this is that it can more clearly convey the constant meaning of development to the code “ Guardian of the future ”.
4.1. What will happen if you don't get used to him
Sometimes we always have a kind of “ Bar fine ” idea ( No , We are here for a more thorough understanding ).
(1) If I have to be const
The modified constant is preceded by mut
What will happen ?
(2) What if I didn't specify the data type when declaring constants ?
(3) If I just want to be Rust
Species modification const
What about modified constants ?
(4) What happens if I don't name constants according to your rules ?
Come on , Let's do experiments one by one , Let practice verify our doubts .
verification (1):
Verify with the following code
fn main() {
const mut THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
}
Trying to perform :
imaginemiracle:variables$ cargo run
Compiling variables v0.1.0 (/home/imaginemiracle/Miracle/Code/rust_projects/variables)
error: const globals cannot be mutable
--> src/main.rs:3:11
|
3 | const mut THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
| ----- ^^^ cannot be mutable
| |
| help: you might want to declare a static instead: `static`
error: could not compile `variables` due to previous error
OK! The compiler directly says that constant expressions cannot become variable variables .( The compiler won't let .)
verification (2):
Verify with the following code
fn main() {
const THREE_HOURS_IN_SECONDS = 60 * 60 * 3;
}
Trying to perform :
imaginemiracle:variables$ cargo run
Compiling variables v0.1.0 (/home/imaginemiracle/Miracle/Code/rust_projects/variables)
error: missing type for `const` item
--> src/main.rs:3:11
|
3 | const THREE_HOURS_IN_SECONDS = 60 * 60 * 3;
| ^^^^^^^^^^^^^^^^^^^^^^ help: provide a type for the constant: `THREE_HOURS_IN_SECONDS: i32`
error: could not compile `variables` due to previous error
OK ! Compiler theory missing type for 'const' item
, We have detected a problem with our grammar , say const
This piece lacks type .( The compiler won't let .)
verification (3):
Verify with the following code
fn main() {
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
THREE_HOURS_IN_SECONDS = 12;
}
Trying to perform :
imaginemiracle:variables$ cargo run
Compiling variables v0.1.0 (/home/imaginemiracle/Miracle/Code/rust_projects/variables)
error[E0070]: invalid left-hand side of assignment
--> src/main.rs:6:28
|
6 | THREE_HOURS_IN_SECONDS = 12;
| ---------------------- ^
| |
| cannot assign to this expression
For more information about this error, try `rustc --explain E0070`.
error: could not compile `variables` due to previous error
OK ! The compiler does not allow this assignment .( The compiler won't let .)
verification (4):
Verify with the following code
fn main() {
const three_HoursIn_seconds: u32 = 60 * 60 * 3;
println!("The result: {three_HoursIn_seconds}");
}
Trying to perform :
imaginemiracle:variables$ cargo run
Compiling variables v0.1.0 (/home/imaginemiracle/Miracle/Code/rust_projects/variables)
warning: constant `three_HoursIn_seconds` should have an upper case name
--> src/main.rs:4:11
|
4 | const three_HoursIn_seconds: u32 = 60 * 60 * 3;
| ^^^^^^^^^^^^^^^^^^^^^ help: convert the identifier to upper case: `THREE_HOURS_IN_SECONDS`
|
= note: `#[warn(non_upper_case_globals)]` on by default
warning: `variables` (bin "variables") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.20s
Running `target/debug/variables`
The result: 10800
Oh, hello ~, The compiler just warns us , But here's the thing , The compiler prompts us to say , Constants should still have a fully capitalized name .( Respect him , Just behave .)
5. Cover (Shadowing)
Rust
It is allowed to declare a new variable with the same name as the previous variable , At this time, the first variable is overwritten by the second new variable (Shadowing
), This will mean that after the second newly declared variable , The variable with the same name that the compiler sees again will change ( There are not two variables with the same name ). Cover (Shadowing
) There are also life-cycle constraints on the variables of . Let's look at an example ( take src/main.rs
The content is modified to the following code ):
fn main() {
let num = 2048;
let num = num / 2; // shadowing
{
let num = num / 2;
println!("The value of num in the inner scope is: {num}");
} // Use {} Set the variable declaration cycle
println!("The value of num is: {num}");
}
analysis :
This code is first num
Bind a value of 2048
. And then through let num
Create a new variable repeatedly num
, And assign it the original value divided by 2
, So the num
The value of should be 1024
.
Then use it again within the limits of a brace let num
Overwrite and create a new num
, The assignment is the previous value divided by 2
, Here's the newly created num
The declaration cycle ends with the end of braces , that shadowing
The effect also disappears . Look again outside the braces num
The value of will revert to the state at the beginning of the brace .
Let's execute and see if the analysis is correct :
imaginemiracle:variables$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/variables`
The value of num in the inner scope is: 512
The value of num is: 1024
Boy: おかしいなあ, This seems to be changing the value of the variable !
Girl: Yes , This really looks like changing the value of a variable .
Boy: ???Rust
Why bother so much and toss around mut
wow !
in fact mut
And shadowing
There are still differences in the process , Use let
Redeclare and overwrite the previous variables , This process really creates a new variable , So we can change the type of white energy at will , But use the same name . Let's illustrate with an example ( take src/main.rs
The content is modified to the following code ):
fn main() {
let hello = "hello world!";
println!("The string is: {hello}");
let hello = hello.len();
println!("The string length is: {hello}");
}
analysis :
Look at this code , First of all, a statement named hello
The variable of , The value bound to it is “hello world!”
, There is no explicit indication of its data type , because Rust
The compiler will automatically recognize it as a string type . And use below let hello
Redeclared a variable with the same name , The value bound to it is original hello
String length of variable , Also, the data type is not explicitly indicated , The compiler will automatically detect integer (Rust
The default integer type in is i32
). So here hello
In fact, it has not only changed the value , The data type it represents has also changed , Except that the name has not changed , Others have been completely transformed .
The execution result of this code is as follows :
imaginemiracle:variables$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/variables`
The string is: hello world!
The string length is: 12
So if you use mut
What's going to happen ? Let's see .
( take src/main.rs
The content is modified to the following code ):
fn main() {
let mut hello = "hello world!";
println!("The string is: {hello}");
hello = hello.len();
println!("The string length is: {hello}");
}
Try to execute it :
imaginemiracle:variables$ cargo run
Compiling variables v0.1.0 (/home/imaginemiracle/Miracle/Code/rust_projects/variables)
error[E0308]: mismatched types
--> src/main.rs:7:13
|
3 | let mut hello = "hello world!";
| -------------- expected due to this value
...
7 | hello = hello.len();
| ^^^^^^^^^^^ expected `&str`, found `usize`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `variables` due to previous error
The compiler will report an error , Prompt us that the type does not match , Cannot assign an integer to a variable of type string .
#Review
OK ! So far, we have clearly understood how to declare variables and , How variables work . Next we will look at Rust
More data types in .
Boys and Girls!!!
are you ready? ? In the next section, we will start to do a little exercise !
No ! I'm not ready yet , Let me review the previous .
Last one 《Rust Language —— Xiaoxiaobai's introductory learning 04》
I'm ready , Hang up かって Come on い( Put your horse here )!
Next 《Rust Language —— Xiaoxiaobai's introductory learning 06》
If you think this article is helpful to you , Just leave a praise v*
Please respect the author , Please indicate the source of the reprint ! Thank you for your cooperation ~
[ author ]: Imagine Miracle
[ Copyright ]: This work adopts knowledge sharing A signature - Non commercial - Share in the same way 4.0 International licensing agreement Licensing .
[ Link to this article ]: https://blog.csdn.net/qq_36393978/article/details/125526797
边栏推荐
- The leader of the cloud native theme group of beacon Committee has a long way to go!
- MySQL5.7 设置密码策略(等保三级密码改造)
- Learn MySQL from scratch - database and data table operations
- 【QT小作】封装一个简单的线程管理类
- 详解ThreadLocal
- 园区全光技术选型-中篇
- MySQL MHA high availability configuration and failover
- cvpr2022 human pose estiamtion
- Redis configuration and optimization
- Compensation des créneaux horaires
猜你喜欢
分享一个一年经历两次裁员的程序员的一些感触
Appium自动化测试基础 — APPium安装(一)
删除AWS绑定的信用卡账户
13th Blue Bridge Cup group B national tournament
SAP GUI 里的收藏夹事务码管理工具
How to write a performance test plan
Object memory layout
Chapter 9 Yunji datacanvas company has been ranked top 3 in China's machine learning platform market
三翼鸟两周年:羽翼渐丰,腾飞指日可待
H5 model trained by keras to tflite
随机推荐
LC669. 修剪二叉搜索树
Tourism Management System
LC501. 二叉搜索树中的众数
3DE 资源没东西或不对
Smart micro mm32 multi-channel adc-dma configuration
nn.Parameter】Pytorch特征融合自适应权重设置(可学习权重使用)
Sonic cloud real machine learning summary 6 - 1.4.1 server and agent deployment
QT版本华睿相机的Demo程序实现
性能测试计划怎么编写
[literacy] deep / shallow, local / global features in machine learning image processing
20220701
Dark horse programmer - software testing - stage 06 2-linux and database-01-08 Chapter 1 - description of the content of the Linux operating system stage, description of the basic format and common fo
Lc669. Prune binary search tree
Clean up system cache and free memory under Linux
Compensation des créneaux horaires
Slope compensation
2020-ViT ICLR
#yyds干货盘点# 解决名企真题:扭蛋机
人体姿态估计的热图变成坐标点的两种方案
【JetCache】JetCache的使用方法与步骤