当前位置:网站首页>Based article 】 【 learn with Rust | Rust, variables and data types
Based article 】 【 learn with Rust | Rust, variables and data types
2022-07-29 11:51:00 【Guang Longyu】
目录
A variable cannot be used until it is initialized
使用 mut Mark the variable as mutable
前言
After the previous studies,大家应该对RustAlready have a preliminary understanding.现在我们将从Rust的基础开始学习.
Variables are a necessary part of a programming language,Learning any programming language requires variables,It's the foundation within the foundation,学习Rust也是这样的.In this issue we will start fromRustThe concept of variables begins,At the same time with the programming case,supplemented by homework,Help everyone learn and understandRustThe basic concept of variables.
一、定义变量
RustDefining variables requires the use of keywordslet,这点和Javascript是一致的,如果你有JS开发的经验,Then you should be familiar with it.Now we define a few variables
let x = 5;
let y = 5.0;
let str = String::from("Hello");All of the above variables are fine,定义了三个变量,x是整数型的,y是浮点型的,zis of type string.除此以外,RustAlso supports specifying a variable type to define variables
let x: i32 = 5;
let y: f64 = 5.0;
let str: String = String::from("Hello");In fact, we do not have to specify the type,因为RustWhich type you are using can be automatically deduced.
二、Rust变量的可变性
在Rust中,变量默认是不可变的.If you write the following code,就会报错
fn main() {
let x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}报错如下
Now let's analyze this error,首先看红色的报错,翻译过来的意思是,Immutable variables cannot be assigned twice.This means that immutable variables cannot be assigned again.
然后我们看蓝色的部分,第一次给x分配值,帮助:考虑使xbecome variable,`mut x`.可以看出,The blue part is what helps us fix this error,这也是RustOne of the stronger places.按照这个提示,We should change this,
let mut x: i32 = 5;
print!("The value of x is: {}", x);
x = 6;
print!("The value of x is: {}", x);At this point we continue to run and see,

因此我们得出结论,RustThe variables are immutable by default,只有添加mutThe keyword will only become later可变.
三、Rust基本数据类型
1.数值类型
数值类型又分为整数型、浮点数、序列类型.
整型
| 长度 | 有符号 | 无符号 |
| 8-bit | i8 | u8 |
| 16-bit | i16 | u16 |
| 32-bit | i32 | u32 |
| 64-bit | i64 | u64 |
| 128-bit | i128 | u128 |
| arch | isize | usize |
其中,Each length is available as both signed and unsigned,The sign indicates that this number is divided into positive and negative numbers,Unsigned means that this data type only has positive numbers.
The range of signed integer values is

其中n是长度.
另外,isize 和 usize The type depends on the architecture of the computer running the program:64 Bit-architecturally they are 64 位的, 32 Bit-architecturally they are 32 位的.
It also supports literals representing different bases in different forms.
| 数字字面值 | 例子 |
|---|---|
| Decimal (十进制) | 98_222 |
| Hex (十六进制) | 0xff |
| Octal (八进制) | 0o77 |
| Binary (二进制) | 0b1111_0000 |
Byte (单字节字符)(仅限于u8) | b'A' |
浮点型
Rust There are also two native ones 浮点数 类型,They are numbers with a decimal point.Rust The floating point type is f32 和 f64,分别占 32 位和 64 位.浮点数采用 IEEE-754 标准表示.f32 是单精度浮点数,f64 是双精度浮点数.默认类型是 f64,因为在现代 CPU 中,它与 f32 The speed is almost the same,But the precision is higher.All floating point types are signed.The following is an example of using floating point.
fn main() {
let x = 2.0; // f64
let y: f32 = 3.0; // f32
}2.字符类型
和C语言一样,char也是Rust的原生类型.但是与之不同的是,Rust的char类型是Unicode的,支持更多的字符,The following are examples of using character types,(If you can copy to Sanskrit,Even Sanskrit can be encoded.)
fn main() {
let c = 'z';
let z: char = 'ℤ'; // 指定变量类型
let heart_eyed_cat = '';
}Be careful to distinguish between characters and strings,字符使用的是单引号,字符串使用的是双引号.
3.布尔类型
Rust The boolean type in has two possible values:true 和 false.Rust The boolean type used in bool 表示.例如:
fn main() {
let t = true;
let f: bool = false; // 指定变量类型
}
四、复合类型
复合类型Multiple values can be combined into a single type.Rust There are two native composite types:元组(tuple)和数组(array).
元组
Tuples are a primary way of combining values of multiple other types into a composite type.You can combine multiple values of different types,但是Tuple length is fixed:一旦声明,Its length does not grow or shrink.
fn main() {
let tup1 = (500, 6.4, 1);
let tup2: (i32, f64, u8) = (500, 6.4, 1); // 指定类型
}
Tuples are also supported解构操作
fn main() {
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("y的值是: {y}");
}The value of a tuple is accessed using the element's index within the tuple,索引是从0开始的,Same with arrays
fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
let x1 = x.0;
let x2 = x.1;
let x3 = x.2;
}数组
与元组不同,数组中的每个元素的类型必须相同.Rust Arrays in are different from arrays in some other languages,Rust中的数组长度是固定的.使用方式如下
fn main() {
let a = [1, 2, 3, 4, 5];
let months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
}
You can also specify the element type
let a: [i32; 5] = [1, 2, 3, 4, 5];If the values in the initialized array are the same,Then there is an easy way to write it,如下,创建了一个数组a,其中有5个元素,These five elements are all integers3
let a = [3; 5];Accessing elements in an array is the same as in other programming languages
fn main() {
let a = [1, 2, 3, 4, 5];
let a1 = a[0];
let a2 = a[1];
}
但是要注意,Don't try to access array elements out of bounds,也就是说,To access elements within the length of the array.
五、常量
Constants and immutables are similar,但是是不同的.常量(constants) is a non-changeable value bound to a name.
- Immutable is immutable by default
- Constants are always immutable
- 常量可以在任何作用域中声明
- 常量只能被设置为常量表达式,Not any other value that can only be calculated at runtime
Declare a constant to useconst
fn main() {
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
}
总结
The above is the content of this issue.本期主要讲了
- 变量的定义
- 变量的可变性
- 基本变量类型
- 整型
- 布尔型
- 字符型
- 复合型
- 数组
- 元组
- 常量
Although very hard to organize the content,But it still doesn't feel right,It must be adjusted later,方便新手入门,so that more people can learnRust.
作业
Complete the following homework for you to learn wellrust的重要组成部分.The following topics are taken from《Rust练习实践》
A variable cannot be used until it is initialized
// Fix errors in the code below with as few modifications as possible
fn main() {
let x: i32; // 未初始化,but is used
let y: i32; // 未初始化,also not used
println!("x is equal to {}", x);
}
使用 mut Mark the variable as mutable
// 完形填空,Let the code compile
fn main() {
let __ = 1;
__ += 2;
println!("x = {}", x);
}
变量解构
// Fix errors in the code below with as few modifications as possible
fn main() {
let (x, y) = (1, 2);
x += 2;
assert_eq!(x, 3);
assert_eq!(y, 2);
}
边栏推荐
- ASN.1接口描述语言详解
- The company has a new product, do you want to hire an agent?
- "100 Interview Knowledge Collections" 1. Interview Skills丨Do you really understand HR's careful thinking?
- 【每日SQL打卡】DAY 22丨页面推荐【难度中等】
- Building and sharing the root of the digital world: Alibaba Cloud builds a comprehensive cloud-native open source ecosystem
- Out-of-the-box problem-solving thinking, putting a "rearview mirror" on the unconscious life
- INVALID_ ARGUMENT : Invalid rank for input: modelInput Got: 3 Expected: 4 Please fix either the input
- Std:: vector copy, append, nested access
- MySql启动、连接sqlog、主从复制、双机热备(开机时)
- 【每日SQL打卡】DAY 27丨列出指定时间段内所有的下单产品【难度简单】
猜你喜欢

CSDN TOP1“一个处女座的程序猿“如何通过写作成为百万粉丝博主

LED透明屏和LED玻璃显示屏区别

MyCat中间件高可用、读写分离、分片、主从切换、ER分片

2.2 Selection sort

【day04】IDEA、方法

MySql启动、连接sqlog、主从复制、双机热备(开机时)

多元宇宙:重塑新商业格局
Based article 】 【 learn with Rust | Rust function and process control, rounding

LeetCode_容斥原理_中等_223.矩形面积

The interviewer training courseware (very practical in-house training courseware)
随机推荐
Collections.singletonList(T o)
微信发红包测试用例
2.3插入排序
c语言:来实现一个小程序n子棋(已五子棋为例)
ECCV 2022 | ssp: a new idea of small sample tasks with self-supporting matching
Learn weekly - 64 - a v2ex style source BBS program
网络层和传输层限制
Based on the flask to write a small shopping mall project
fastjson使用方法
解决idea在debug模式下变得非常慢的问题
QML(一):自定义圆角按钮的处理
【每日SQL打卡】DAY 23丨向CEO汇报工作的人【难度中等】
MySql启动、连接sqlog、主从复制、双机热备(开机时)
PL/SQL 集合
迁徙数据平台简单介绍
three.js 报错信息 RGBELoader.js:46 RGBELoader Bad File Format: bad initial token
Dawei gbase8s cursor stability read esql test case
Proficient in audio and video development can really do whatever you want
力扣sql刷题(四)
DAY 20 daily SQL clock 】 【 丨 query results of quality and than simple difficult 】 【
