Rust学习总结之数组,元组,结构体用法

         学过数据结构的都知道有这么一个公式,程序=数据结构+算法,好的数据结构能大大降低算法设计的复杂度,也能更好的为算法服务。了解一门新的计算机编程语言其数据结构是必须首先要学的,这有利于对该语言的理解和快速上手。本文将对Rust语言中的数组,元组,结构体的用法进行详细的介绍

目录

1,数组

2,元组

3,结构体


1,数组

        用过C语言的相信对数组的概念并不陌生,用过Python的看到Rust的数组形式想必十分的亲切。数组 array,将多个类型相同的元素依次组合在一起,就是一个数组。

        数组的三个原则:

  • 长度固定                        ----数组的长度是固定的,初始化后长度就固定了
  • 元素必须有相同的类型  ----数组的元素必须是一样的类型
  • 依次线性排列                 ----数组的元素在内存中是在一起的

 举例:

fn main() {
    let s = ['f', 'e', 'i','t','z'];
}

        上面就是一个最简单的数组例子,里面包含了5个元素,在vscode中会自动在后面显示元素类型和元素的个数

当然你也可也以显示的写出来

fn main() {
    let s:[char;5] = ['f', 'e', 'i','t','z'];
}

访问数组的的某个元素和C语言中一样,通过下标来访问,下标从0开始

fn main() {
    let s:[char;5] = ['f', 'e', 'i','t','z'];
    println!("array s first element is {}",s[0]);
}

 遍历数组常见的有两种方式,一是通过数组下标去遍历,二是通过数组的可迭代属性去遍历

fn main() {
    let s:[char;5] = ['f', 'e', 'i','t','z'];
    //遍历数组s,方法一
    for index in 0..s.len(){
        println!("遍历数组:s[{}]:{}",index,s[index]);
    }
    //遍历数组s,方法二
    for element in s.iter(){
        println!("遍历数组s:{}",element);
    }
}

运行结果:

遍历数组:s[0]:f
遍历数组:s[1]:e
遍历数组:s[2]:i
遍历数组:s[3]:t
遍历数组:s[4]:z
遍历数组s:f
遍历数组s:e
遍历数组s:i
遍历数组s:t
遍历数组s:z

        上面计算数组的长度可以调用数组的len()方法

2,元组

        上面提到数组只能放入相同类型的元素,在Rust中有没有一种结构能放入不同类型的元素呢,元组就能符合这样的要求。元组的概念不是Rust独有的,在Python中也有元组,Rust元组的形式和Python很像。

Rust 语言中元组的定义语法格式如下:

let tuple_name:(data_type1,data_type2,data_type3) = (value1,value2,value3);

定义元组时也可以忽略数据类型

let tuple_name = (value1,value2,value3);

        The definition of a tuple in Rust is very simple. It uses a pair of parentheses  () to put all the elements together, and the elements are  , separated by commas. But it should be noted that if the data type of the tuple is explicitly specified, the number of data types must be the same as the number of tuples

Below we define a tuple and print out the tuple

fn main() {
    let eg_tupple = ('f', 30, 174.5);
    println!("my info is {:?}",eg_tupple);
}

operation result:

my info is ('f', 30, 174.5)

We can use  元组名.索引数字 to access the element at the corresponding index position in the tuple. index from  0 the beginning. 

fn main() {
    let eg_tupple = ('f', 30, 174.5);
    println!("my age is {}",eg_tupple.1);
    println!("my height is {}",eg_tupple.2);
}

operation result:

my age is 30
my height is 174.5

3. Structure

        The main event is coming. Due to the fixed structure of arrays and tuples, they are destined not to undertake too complex data structure design. Structures can undertake complex data structure designs with their flexible structures. The use of structures in C language is very Broadly, although there is no concept of structure in Python, the dictionary structure in Python is very similar to Rust's structure. Let's take a closer look at Rust's structure

The syntax for defining a structure is as follows

struct Name_of_structure {
   field1:data_type,
   field2:data_type,
   field3:data_type
}

When defining a struct:

  1. Structure names  Name_of_structure and element/field names  fieldN follow the naming syntax of ordinary variables.
  2. Each element/field in the structure must explicitly specify the data type. Can be a primitive type, or another struct.

Below we define a structure and instantiate it

struct User{
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}
fn main() {
    let user1 = User{
        email: String::from("[email protected]"),
        username: String::from("ftz"),
        active: true,
        sign_in_count: 556,
    };
}

        We define a structure User, and instantiate user1. When instantiating user1, it is not necessary to initialize the variables in strict accordance with the order of the structure definition. It should be noted that when we initialize, all members must be initialized, and partial initialization is not possible. part not written

If we want to access an element of a structure instance, we can use  the element accessor , which is  the dot (  . ) 

struct User{
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}
fn main() {
    let user1 = User{
        email: String::from("[email protected]"),
        username: String::from("ftz"),
        active: true,
        sign_in_count: 556,
    };
    let my_name = user1.username;
    println!("my name is {}",my_name);
}

         The structure instance is  not modifiable by default , because the structure instance is also a defined  let variable. If you want to modify the structure instance, you must add keywords when creating it  mut to make it modifiable

When you want to create a new instance based on a struct instance, you can use the struct update syntax

#[derive(Debug)]
struct User{
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}
fn main() {
    let user1 = User{
        email: String::from("[email protected]"),
        username: String::from("ftz"),
        active: true,
        sign_in_count: 556,
    };
    let user2 = User{
        username: String::from("zte"),
        ..user1
    };
    println!("my info is {:#?}",user2);
}


 operation result:

my info is User {
    username: "zte",
    email: "[email protected]",
    sign_in_count: 556,
    active: true,
}

 There is also a tuple struct concept in the Rust structure. The tuple structure has a name as a whole, but the elements inside have no names. The applicable scenario is that you want to name the entire tuple and make it different from other tuples, but you don't need to name each element.

#[derive(Debug)]

fn main() {
    struct Color(i32, i32, i32);
    struct Point(i32, i32, i32);
    let black = Color(0,0,0);
    let origin = Point(0,0,0);
}

black and origin are different types, even if the elements in their tuples are the same, they are different tuple struct instances

Next, we use struct to write a relatively complete Rust program to calculate the area of ​​a rectangle, so that it is easier for everyone to understand the structure

#[derive(Debug)]
struct Rectangle{
    width: u32,
    length: u32,
}
fn main() {
    let rect = Rectangle{
        width: 30,
        length: 50,
    };
    println!("the area is {}",area(&rect));
    println!("the rect is {:#?}",rect);
}

//此处用引用&,就是借用rect, 在main中不丧失rect的所有权
fn area(rect: &Rectangle) ->u32{
    rect.width * rect.length
}

 operation result:

the area is 1500
the rect is Rectangle {
    width: 30,
    length: 50,
}

alright! ! ! The above is a summary of the study of Rust arrays, tuples, and structures. If there is something wrong, you are welcome to criticize and correct. It is better to like it, hehehe! ! !

Guess you like

Origin blog.csdn.net/qq_27071221/article/details/129330962