Rust study notes 3.2 structure

3.2 Structure

  • There is no class in rust

struct

  • Types that contain multiple pieces of data
  • Each piece of data is called fieldan attribute
  • Access properties with.
#[derive(Debug)]
struct Rectangle {
    
    
    width: i32,
    height: i32,
}
fn main() {
    
    
    let rect = Rectangle {
    
    
        width: 5,
        height: 10,
    };
    println!("{}", rect.width);
    println!("{:#?}", rect);
}

struct method

  • Correlation function
  • instance method
  • Constructor
  • Self

Example 1

#[derive(Debug)]
struct Rectangle {
    
    
    width: i32,
    height: i32,
}

impl Rectangle {
    
    
    // 关联函数
    fn area(width: i32, height: i32) -> i32 {
    
    
        width * height
    }
    // 实例方法
    fn cal(&self) -> i32 {
    
    
        self.width * self.height
    }
    // 构造函数
    fn new(width: i32, height: i32) -> Self {
    
    
        Rectangle {
    
     width, height }
    }
}

fn main() {
    
    
    let rect = Rectangle {
    
    
        width: 5,
        height: 10,
    };
    let num1 = Rectangle::area(5, 5);
    println!("{}", num1);
    println!("{}", rect.cal());
    let rect2 = Rectangle::new(5, 5);
    println!("{:#?}", rect2);
}

Example 2

#[derive(Debug)]
struct Person {
    
    
    name: String,
    age: i32,
}

impl Person {
    
    
    // 可能在外部调用,使用pub关键字
    pub fn new(name: String, age: i32) -> Self {
    
    
        Person {
    
     name, age }
    }
}

fn main() {
    
    
    let person1 = Person::new("Star-tears".to_string(), 18);
    println!("{:#?}", person1);
}

  • &self
  • &mut self
  • self
  • mut self

Example 3

#[derive(Debug)]
struct Person {
    
    
    name: String,
    age: i32,
}

impl Person {
    
    
    // 可能在外部调用,使用pub关键字
    pub fn new(name: String, age: i32) -> Self {
    
    
        Person {
    
     name, age }
    }
    fn greet(&self) -> String {
    
    
        format!("Hi {}", self.name)
    }
    fn add_age(&mut self, n: i32) {
    
    
        self.age += n;
    }
}

fn main() {
    
    
    let mut person1 = Person::new("Star-tears".to_string(), 18);
    println!("{:#?}", person1);
    println!("{}", person1.greet());
    person1.add_age(3);
    println!("{}", person1.age);
}

&It is a reference, but it is immutable by default. If you want to be variable, you need to add mutkeywords

Guess you like

Origin blog.csdn.net/qq_51173321/article/details/125947270