Rust Tutorial

Time:2022-11-25

structure

For the definition and use of rust structures, only a few points that need special attention are explained, and the basic usage is not described.

  1. Shorthand syntax when the variable has the same name as the field name
    It can directly correspond to the variable name of each field, without using the method of field name: variable name

    struct Book {
     name:String,
     price:f32,
     pages:u32,
     author:String,
     publishingHouse:String,
    }
    
    fn initBook(name:String, price:f32, pages:u32, author:String, publishingHouse:String) -> Book {
     Book { 
         name,
         price, 
         pages, 
         author,
         publishingHouse,
     }
    }
  2. Reference type structure field
    Storing reference data needs to add a life cycle, otherwise an error will be reported during compilation (the life cycle will be explained in the next section)

    struct DataRef{
     elementRef1:&str, //Error:missing lifetime specifier
     elementRef2:&i32, //Error:missing lifetime specifier
    }

    change to

    struct DataRef<'a> {
     elementRef1:&'a str,
     elementRef2:&'a i32,
    }

    It can be compiled and passed. where ‘a is the definition lifetime

  3. Assignment between structures
    Part of the information in an existing structure can be assigned to the new structure

     #[derive(Debug)]
     struct Book {
         name:String,
         price:f32,
         pages:u32,
         author:String,
         publishingHouse:String,
     }
    
     let book1 = initBook(
         String::from("Cray rust"), 
         88.0, 
         600, 
         String::from("Jack"), 
         String::from("xxx"));
         
     let book2 = Book{
         name:String::from("Master rust"),
         price:96.0,
         pages: 800,
         ..book1
     };
    
     println!("{:?}", book2);
     //println!("{:?}", book1); //Error:borrow of partially moved value: `book1`

    The author and publisher information in book1 is the same as that in book2, we can copy the value in book1 through ..book1 when assigning value to book2.

    Let’s also note that

    • If we use book1 after ..book1, an error will be reported when compiling: borrow of partially moved value:book1This is because the author and publishingHouse in book1 have already transferred ownership
    • There is this sentence #[derive(Debug)] above the structure definition. This is importing the debug library#[derive(Debug)]
    • In println!, you can use the {:?} placeholder to output an entire structure, or you can use {:#?} to optimize the output structure display
  1. tuple structure
    Tuples have been introduced before, and the tuple structure is to define the structure in the form of tuples. The existence of the tuple structure is for convenience. Look at an example to understand, define the coordinate position, color, etc. can be simply and conveniently use the tuple structure

     struct RGB(u32,u32,u32);
     struct Position(f32, f32,f32);
    
     let Red = RGB(255,0,0);
     let StartPosition = Position(10.0, 10.0, 0.0);
    
     println!("Red({},{},{})", Red.0, Red.1, Red.2);
     println!("StartPositon({},{},{})", StartPosition.0, StartPosition.1, StartPosition.2);
  2. method
    The method is similar to the function introduced before, but the method is for the structure.
    The first parameter of the structure method is self, which does not need to be declared, and self is a keyword.
    The use of self is similar to this in C++, but it cannot be compared with this in C++.
    struct Rectangle {
        width: u32,
        height: u32,
    }

    impl Rectangle {
        fn area(&self) -> u32 {
            self.width * self.height
        }

        fn compare(&self, rec:&Rectangle) -> bool {
            if self.area() > rec.area() {
                true
            } else {
                false
            }
        }
    }

    let rec1 = Rectangle{width:10, height:10};
    let rec2 = Rectangle{width:12, height:9};

    println!("Is rec1 larger than rec2:{}", rec1.compare(&rec2));

6. Correlation function
Function As mentioned before, an associated function is a function associated with a structure. I have used the String::from(“xxx”) function before, which is the associated function of String.
The associated function does not depend on the instance and can be understood as a C++ constructor.
Associated functions are also implemented in the impl area, but self is not required

    struct Rectangle {
        width: u32,
        height: u32,
    }

    impl Rectangle {
        fn constructor(width:u32, height:u32) -> Rectangle{
            Rectangle{width,height}
        }

        fn area(&self) -> u32 {
            self.width * self.height
        }

        fn compare(&self, rec:&Rectangle) -> bool {
            if self.area() > rec.area() {
                true
            } else {
                false
            }
        }
    }

    let rec1 = Rectangle::constructor(10, 10);
    let rec2 = Rectangle::constructor(12, 9);