当前位置:网站首页>Rust from entry to proficient 04 - data types

Rust from entry to proficient 04 - data types

2022-08-09 13:17:00 51CTO

Rust 是 静态类型statically typed)语言,That is, the types of all variables must be known at compile time.

在 Rust 中,Every value belongs to one 数据类型data type),分为两大类:

①、标量(scalar):整型、浮点型、布尔类型、字符类型

②、复合(compound):元祖(tuple)、数组(array)、结构体(struct)

1、标量scalar

Each type has a separate value.

1.1 整型

Represents a number without a fractional part,分为有符号(以 i 开头)和无符号(以 u 开头)整型.

The default type for numeric types is i32.

长度

有符号

无符号

8-bit

​i8​

​u8​

16-bit

​i16​

​u16​

32-bit

​i32​

​u32​

64-bit

​i64​

​u64​

128-bit

​i128​

​u128​

arch

​isize​

​usize​

Every signed integer can store inclusive slaves -(2^{n - 1}) 到 2^{n - 1} - 1 numbers inside,这里 n is the length of the integer definition.所以 ​​i8​​​ can be stored from -2^7到 2^7 - 1 numbers inside,也就是从 -128 到 127.Unsigned variants can be stored from 0 到 2^{n - 1} 的数字,所以 ​​u8​​ can be stored from 0 到 2^8 - 1 的数字,也就是从 0 到 255.

另外,​​isize​​​ 和 ​​usize​​ 类型依赖运行程序的计算机架构:64 位架构上它们是 64 位的, 32 位架构上它们是 32 位的.

1.1.1 All numeric literals,You can add underscores anywhere_

      
      
fn int_test(){
//All numeric literals,You can add underscores anywhere_
let x : u32 = 1_2_3;
let y = x + 1;
//打印结果为 124
println!("{}",y);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

1.1.2 A literal can be suffixed with a type,Represents a concrete type of number

      
      
//A literal can be suffixed with a type,Represents a concrete type of number
fn int_test2(){
let x = 123i32;
let y = x + 1;
//打印结果为 124
println!("{}",y);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

1.1.3 Call the function directly on the integer literal

      
      
//Call the function directly on the integer literal
fn int_test3(){
let x : i32 = 9;
//打印结果为 729
println!("9 power 3 = {}",x.pow(3));
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

1.1.4 整数溢出

Rust The handling of integer overflow is as follows: ①、默认情况下,在debug模式下编译器会自动插入整数溢出检查,一旦发生溢出,则会引发 panic; ②、在 release 模式下,不检查整数溢出,It is a way of automatically discarding the high bits.

1.1.5 如何选择

Usually the default type i32 即可,It's usually the fastest.

1.2 浮点

Rust There are two native ones 浮点数floating-point numbers)类型,它们是带小数点的数字.是基于 IEEE 754-2008 Standard floating point type,分别是 ​​f32​​​ 和 ​​f64​​​,分别占 32 位和 64 位.默认类型是 ​​f64​​​,因为在现代 CPU 中,它与 ​​f32​​ 速度几乎一样,不过精度更高.

      
      
fn float_test(){
//123.0 f32类型
let f1 = 123.0f32;
//0.1 f64类型
let f2 = 0.1f64;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

1.3 布尔类型

布尔类型(bool)代表的是“是”和“否”的二值逻辑.它有两个值:

true和false

Generally used in logical expressions,可以执行“与”“或”“非”等运算.

      
      
fn bool_test(){
let x = true;
//取反运算
let y = !x;

//逻辑与,With short circuit function
let z = x && y;

//逻辑或,With short circuit function
let z = x || y;

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

1.4、字符类型

The character type is given by char 表示.It can describe any match unicode 标准的字符值.在代码中,Single character literals are enclosed in single quotes(different from strings):

1.4.1 4个字节字符

      
      
let heart_eyed_cat = '';
  • 1.

因为 char Types are designed to describe either one unicode 字符,So the memory space it occupies is not1个字节,而是 4 个字节.

That means it can be compared ASCII Indicates more.在 Rust 中,拼音字母(Accented letters),中文、日文、韩文等字符,emoji(绘文字)as well as zero-length whitespace characters are valid ​​char​​​ 值.Unicode A scalar value contains from ​​U+0000​​​ 到 ​​U+D7FF​​​ 和 ​​U+E000​​​ 到 ​​U+10FFFF​​ 在内的值.

1.4.2 1个字节字符-u8

let x : u8 = 1;

对于 ASCII Characters actually only need to occupy one byte of space,因此Rust Single-byte character literals are provided to represent them ASCII 字符.

注意:We can also pass a letter b 在字符或者字符串前面,代表这个字面量存储在 u8 类型数组中,这样占用空间比 char 型数组要小一些.

let x : u8 = 1; let y : u8 = b'A';

2、复合compound

复合类型Compound types)可以将多个值组合成一个类型

2.1 元祖(tuple)

①、由圆括号()Contains a set of expressions;

②、长度固定,一旦声明,其长度不会增大或缩小.

③、rustDifferent types of data types can be stored in

2.1.2 实例

      
      
fn tuple_test1(){
//包含两个元素:1和false
let a = (1i32,false);
//包含两个元素:1和元祖,The tuple contains two characters1和2
let b = (1,("1","2"));
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

2.1.3 如果元祖只有一个元素,A comma should be added,Used to distinguish between parenthesized expressions and tuples

      
      
//如果元祖只有一个元素,A comma should be added,Used to distinguish between parenthesized expressions and tuples
fn tuple_test2(){
//a 是一个元祖,只有一个元素1
let a = (1,);
//b 是一个括号表达式,它是 i32类型
let b = (1);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

2.1.4 Access the tuple element

①、Pattern matching destructuring

      
      
//元祖:模式匹配
fn tup_test4(){
let tup = (1,1.1,2);
let (x,y,z) = tup;
println!("x={},y={},z={}",x,y,z);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

②、数字索引

      
      
//元祖:数字索引
fn tup_test5(){
let tup = (1,1.1,2);
println!("x={},y={},z={}",tup.0,tup.1,tup.2);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

2.2 数组(array)

①、by square brackets[] Contains a set of expressions;

②、数组中每个元素的类型必须相同(元祖tuple可以不同);

③、长度固定,一旦声明,其长度不会增大或缩小.

2.2.1 实例

There are three ways to declare.

      
      
//数组:实例
fn array_test1(){
//1、Omit type and length
let a = [1,1,1,1];

//2、Declare the type and length
let b:[i32;4] = [1,1,1,1];

//3、Declare initial value and length
let c = [1;4];

println!("{}",a == b);//true
println!("{}",a == c);//true
println!("{}",c == b);//true
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

2.2.2 访问数组元素

①、通过下标访问

The initial subscript is 0

      
      
//数组:访问元素
fn array_test2(){
let a = [1,2,3,4];
println!("a[0]={}",a[0]);
println!("a[1]={}",a[1]);
println!("a[2]={}",a[2]);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

②、通过 get() 方法

注意返回值是 Option<T>

      
      
//数组:访问元素
fn array_test3(){
let a = [1,2,3,4];
let first = a.get(0);
let last = a.get(4);
println!("{:?}",first);//Some(1)
println!("{:?}",last);//None
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

2.2.3 数组越界访问异常

If the declared array has4个,But access subscript greater than or equal to4,则会在运行时抛出异常(编译能过).

      
      
//数组:访问元素
fn array_test3(){
let a = [1,2,3,4];
println!("a[4]={}",a[4]);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

Rust从入门到精通04-数据类型_字面量

2.2.4 Avoid array out-of-bounds program crashes

If we are not sure if it is legal to read the index of the array,The above access through the index will cause an exception,导致程序奔溃.

为了避免这种情况,我们可以使用 get(index) method to get an element in an array,其返回值是 Option<T>

      
      
//数组:访问元素
fn array_test3(){
let a = [1,2,3,4];
let first = a.get(0);
let last = a.get(4);
println!("{:?}",first);//Some(1)
println!("{:?}",last);//None
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

2.3 结构体(struct)

Structures are similar to primitives,Multiple types can be combined together,as a new type. Structures can be divided into three specific types:

      
      
// 具名结构体
struct Name_Struct {
x : f32,
y : f32,
}
// 元祖结构体
struct Tuple_Struct(f32,f32);

// 单元结构体
struct Unit_Struct;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

2.3.1 具名结构体

      
      
//结构体
fn struct_test1(){
struct Point{
x : i32,
y : i32,
}
let p = Point{x:0,y:0};
println!("{},{}",p.x,p.y);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

①、Separate each element with a comma,The last comma can be omitted. ②、The type still follows the colon,But automatic type deduction cannot be used,必须显示指定.

Local variables are the same as structure variables,Repeated colon initialization can be omitted

      
      
//Local variables are the same as structure variables,Repeated colon initialization can be omitted
fn struct_test2(){
struct Point{
x : i32,
y : i32,
}
let x = 10;
let y = 20;
let p = Point{x,y};
println!("{},{}",p.x,p.y);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

2.3.2 元祖结构体tuple struct

这是前面介绍的 tuple 和 struct A mix of both types,tuple struct Structures have names,But the members don't have names.

Parentheses around the name,Types have separate names,Members do not have individual names.

      
      
fn tuple_struct(){
struct Color (
i32,
i32,
i32
);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

访问方法

通过下标访问:

      
      
fn tuple_struct(){
struct Color (
i32,
i32,
i32
);

let v1 = Color(1,2,3);
println!("{},{},{}",v1.0,v1.1,v1.2)
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

2.3.3 单元结构体

      
      
// 单元结构体
struct Unit_Struct;
  • 1.
  • 2.

Cell structures do not take up any memory space.

3、枚举 enum

如果说 tuple、struct、tuple struct 在 Rust represents multiple types“与”关系,那么 enurn类型在 Rust represents multiple types“或”关系.

Rust 的 enurn The definition syntax for each element in struct The definition syntax is similar.Can be like an empty struct,Do not specify its type;也可以像 tuple struct 一样,Use parentheses to add unnamed members;Also works like a normal struct,Use curly braces to add named members.

      
      
fn main() {
let x = enum_define::Int(12);
let y = enum_define::Float(3.2);
let z = enum_define::Move {x:1,y:2};
let k = enum_define::Color(255,255,255);
match x {
enum_define::Int(i) => {
println!("{}",i);
},
enum_define::Float(f) => {
println!("{}",f);
},
enum_define::Move{x,y} => {
println!("{} {}",x,y);
},
enum_define::Color(x,y,z) => {
println!("{}{}{}",x,y,z);
}
}
}

enum enum_define{
Int(i32),
Float(f32),
Move{x:i32,y:i32},
Color(i32,i32,i32),
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

4、特殊数据类型

4.1 Never 类型

Represents a data type for which no return value is possible.

①、in type theory,called the bottom type,The base type does not contain any value,But it can be combined into any other type;

②、Never Type with an exclamation mark“!" 表示;

③、Not yet stable,但是rustInternal use has already started.

5、常见错误

5.1 Type conversion must be passed as 关键字显式声明

      
      
//Type conversion must be passed as 关键字显式声明
fn switch_test(){
let var1 : i8 = 1;
let var2 : i32 = var1;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

报错如下:

Rust从入门到精通04-数据类型_数组_02

增加 as The keyword display statement is sufficient.

      
      
//Type conversion must be passed as 关键字显式声明
fn switch_test(){
let var1 : i8 = 1;
let var2 : i32 = var1 as i32;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

5.2 Compound data types allow recursion,But direct nesting is not allowed

      
      
//Compound data types do not allow direct nesting
fn recursive(){
struct recur {
data : i32,
rec : recur
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

报错如下:

Rust从入门到精通04-数据类型_字面量_03


原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208091152354489.html