当前位置:网站首页>Rust from entry to proficient 04-variables
Rust from entry to proficient 04-variables
2022-08-04 14:03:00 【[Illusory private school]】
优质资源分享
学习路线指引(点击解锁) | 知识定位 | 人群定位 |
---|---|---|
🧡 Python实战微信订餐小程序 🧡 | 进阶级 | 本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统. |
Python量化交易实战 | 入门级 | 手把手带你打造一个易扩展、更安全、效率更高的量化交易系统 |
目录 |
回到顶部### 1、变量声明语法
Rust 变量必须先声明,后使用.
对于局部变量,Common is to declare the syntax as :
let variable : i32 = 100;
由于 Rust There is an automatic type deduction function,所以后面的 :i32 是可以省略的.
1.1 Syntax parsing is easier
Local variable declarations must be let 开头,The type must be followed by a colon : 的后面.语法歧义更少,语法分析器更容易编写.
1.2 It is convenient to introduce type deduction function
Rust 声明变量的特点:要声明的变量前置,Type description is appended.
This is because in the variable declaration statement,最重要的是变量本身,The type is actually an attached additional description,并非必不可少的部分.If we can automatically analyze the type of this variable by the compiler through the context environment,Then this type description can be omitted completely.
PS:Rust 支持类型推导,In the case where the compiler is able to deduce the type,The variable type can generally be omitted,但常量(const)和静态变量(static)必须声明类型.
Rust Type auto-deduction was considered from the start,Therefore, the type-poster syntax is more appropriate.
1.3 模式解构
pattern destructure
For example, changing a variable from read-only to read-write(mut声明)
回到顶部### 2、变量命名规则
Rust legal identifiers in (包括变量名、函数名、trait名等)必须由:
①、数字
②、字母
③、下划线
注意:不能以数字开头!!!
另外:Note the underscore _ 的特殊用法.
回到顶部### 3、变量遮蔽
Rust Variables with the same name can be declared in the same block of code,Variables declared later will replace variables declared earlier“遮蔽”起来.
//变量遮蔽
fn variable\_masking(){
let x = "123";
println!("{}",x);
let x = 1;
println!("{}",x);
}
注意:Doing so does not create memory safety issues,Because we have full ownership of this memory,And there are no other references to this variable at this time,Modifications to this variable are perfectly legal.
回到顶部### 4、变量类型推导
RustThere are two types of type deduction:
①、Deduces information from the current statement of the variable declaration
②、Derive from contextual information
//类型推导
fn type\_derivation(){
//1.1 The variable type is not explicitly marked,But via literal suffix,编译器知道x的类型是 u8
let x = 5u8;
//1.2 by literal value 1,编译器知道y 的类型是 i32
let y = 1;
//1.3 创建一个动态数组,But there is no declaration of what type is in the array
let mut vec = Vec::new();
//The compiler passes the added element 1 ,推导出 vec 的实际类型是 Vec
vec.push(1);
println!("{}",x);
println!("{}",y);
println!("{:?}",vec);
}
回到顶部### 5、类型别名
通过 type 关键字给同一个类型起个别名.
//类型别名
fn type\_alias(){
//将 i32 This data type is aliased as int
type int = i32;
let x : int = 1;
println!("{}",x);
}
Type aliases can also be used in generic scenarios:
type Double = (T,Vec);
那么,以后使用 Double 的时候,就等同于(i32,Vec)
回到顶部### 6、不可变 mut
Rust Declared variables are immutable by default.
默认不可变,这是一个很重要的特性,It conforms to the principle of least privilege,Helps us write correct and robust code.
// 变量不可变
fn variable\_mut(){
let i = 123;
i = 2;
}
编译报错:
If you want to make the variable mutable,Keywords must be used mut
声明:
fn variable\_mut(){
let mut i = 123;
i = 2;
}
当你使用 mut The variable is not modified,Rust Compile time will be friendly alarm,Prompt you to remove unnecessary ones mut.
fn main() {
variable\_mut();
}
// 变量不可变
fn variable\_mut(){
let mut i = 123;
println!("{}",i);
}
编译器警告:
回到顶部### 7、静态变量
Rust 中通过 static 关键字声明静态变量,如下:
static GLOBAL : i32 = 0;
static The lifetime of the declared variable is the entire program,从启动到退出,static The lifetime of a variable is always ‘static’,The memory space it occupies will not be reclaimed during execution.
这也是 Rust The only way to declare a global variable in .
由于 Rust 非常注重内存安全,Therefore there are many restrictions on the use of global variables:
①、Global variables must be initialized immediately upon declaration(Corresponding local variables can be declared without initialization,Just make sure to initialize it when you use it,我们可以这样理解,Global variables are written outside the function,Local variables are written inside the function,Therefore, it is necessary to ensure that global variables are initialized when they are declared);
②、The initialization of global variables must be constants that can be determined at compile time,Expressions that are determined only at execution time cannot be included、语句和函数调用;
③、带有 mut 修饰的全局变量,在使用的时候必须使用 unsafe 关键字.
回到顶部### 8、常量
Rust 中通过 const 关键字声明常量.如下:
const GLOBAL : i32 = 0;
①、使用 const 声明的是常量,而不是变量.因此不允许使用 mut The keyword decorates this variable binding.
②、A constant's initializer must also be a compile-time constant,Cannot be a runtime value.
注意:const 和 static The big difference is that the compiler doesn't necessarily give it const 常量分配内存空间,在编译过程中,It will most likely be optimized inline.
回到顶部### 9、Common mistakes in variable declarations
9.1 Variables must be initialized before they can be used
Types do not have default constructors,variable value no“默认值”
fn main() {
let x : i32;
println!("{}",x);
}
9.2 不能通过 mut 关键字修饰 const 声明的变量
这个很容易理解,常量是不可变的,mut 表示可变,Put together a semantic conflict.
//mut和 const 不能一起使用
fn const\_mut\_error(){
const mut i : i32 = 1;
println!("{}",i);
}
边栏推荐
- 按键控制开关4017芯片数字电路
- router---dynamic route matching
- ICML 2022 | 图神经网络的局部增强
- LeetCode 1403 Minimum subsequence in non-increasing order [greedy] HERODING's LeetCode road
- router---Programmatic navigation
- 从理论到实践:MySQL性能优化和高可用架构,一次讲清
- 记录都有哪些_js常用方法总结
- Convolutional Neural Network Basics
- 汉诺塔怎么玩
- 【WeChat Mini Program】Social Internship Production Project for Information Management and Information System Major--Trash Fingerprint
猜你喜欢
【模型部署与业务落地】基于量化芯片的损失分析
This article sorts out the development of the main models of NLP
Execution failed for task ‘:xxx:generateReleaseRFile‘.
【LeetCode】38、外观数列
九州云出席领航者线上论坛,共话5G MEC边缘计算现状、挑战和未来
牛客网刷题记录 || 链表
"C pitfalls and pitfalls" reading summary
Button control switch 4017 digital circuit chip
MySQL【窗口函数】【共用表表达式】
代码越写越乱?那是因为你没用责任链!
随机推荐
Is the code more messy?That's because you don't use Chain of Responsibility!
idea permanent activation tutorial (new version)
k8s上安装mysql
记录都有哪些_js常用方法总结
漏洞复现 - - - Alibaba Nacos权限认证绕过
router---Programmatic navigation
LM2596有没有可以替代的?LM2576可以
文字编码 - XML 教程
开放麒麟 openKylin 版本规划敲定:10 月发布 0.9 版并开启公测,12 月发布 1.0 版
Interviewer: Tell me the difference between NIO and BIO
router---mode
AlphaFold 如何实现 AI 在结构生物学中的全部潜力
【LeetCode】38、外观数列
TS---类型设置
面试官:如何查看/etc目录下包含abc字符串的文件?
JSX use
leetcode 48. Rotate Image (Medium)
字符串类的设计与实现_C语言字符串编程题
Analysis and application of portrait segmentation technology
ssm学习心得(完结篇