struct

结构体,里面是参数名以及参数的类型

struct Rectangle {
    width: u32,//逗号结尾是因为这是结构体定义的字段,规定用,分隔
    height: u32,
}

impl

定义方法,在块中定义函数,以便在其他地方使用,使用方法就是令一个自定义参数=结构体带对应参数,再直接跟方法名即可,如下代码中rect1所示

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}
fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };

    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );
}

&self

在impl定义的块中,使用&self表示Rectangle自身,self在rust的很多地方都可以用来代指所在位置的实例,比如slint中可以用self代指self所在控件。

需要注意self也有所有权

  • self 表示 Rectangle 的所有权转移到该方法中,这种形式用的较少
  • &self 表示该方法对 Rectangle 的不可变借用
  • &mut self 表示可变借用
impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

方法名跟结构体字段名相同

在rust中允许方法名和结构字段名相同,这里引入一个东西叫getter 访问器(见概念.md),这种方法的好处是把结构中的参数设为私有,不让外界访问,但可以在方法里定义一个函数去获取结构体的参数,实现getter 访问器的效果。

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

impl Rectangle {
    pub fn new(width: u32, height: u32) -> Self {
        Rectangle { width, height }
    }
    pub fn width(&self) -> u32 {//定义width()方法,这里使用&self表示对这个方法的不可变借用
        return self.width;//返回结构体的width参数,这里使用self表示把结构体的所有权转移到这里
    }
}

fn main() {
    let rect1 = Rectangle::new(30, 50);

    println!("{}", rect1.width());
}

方法和函数一样可以有多个参数

impl Rectangle {
    fn area(&self) -> u32 {//Rectangle的第一个参数area
        self.width * self.height
    }

    fn can_hold(&self, other: &Rectangle) -> bool {//Rectangle的第二个参数can_hold
        self.width > other.width && self.height > other.height
    }
}

fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };
    let rect2 = Rectangle { width: 10, height: 40 };
    let rect3 = Rectangle { width: 60, height: 45 };

    println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
    println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}

关联函数

impl Rectangle {
    fn new(w: u32, h: u32) -> Rectangle {
        Rectangle { width: w, height: h }
    }
}

这段代码中没有self,所以不能称为方法,但又是impl结构体,所以要把它称为关联函数,因为是函数,所以不能用 . 的方式来调用,我们需要用 :: 来调用,例如 let sq = Rectangle::new(3, 3);。这个方法位于结构体的命名空间中::: 语法用于关联函数和模块创建的命名空间。

最后修改:2024 年 05 月 05 日
如果觉得我的文章对你有用,请随意赞赏