Rust入门笔记 5.方法和关联函数

yyi
yyi
2023-09-06 / 0 评论 / 75 阅读 / 正在检测是否收录...

使用 impl "struct_name" 的方式声明关联函数

struct Point {
    x: f64,
    y: f64,
}
impl Point {
    fn origin() -> Point {
        Point { x: 0.0, y:0.0 }
    }
    
    fn new(x: f64, y:f64) -> Point {
        Point {x:x, y:y}
    }
}

在第一个参数处声明一个Self类型的变量,以为结构创建方法

self <=> self: Self
&self <=> self: &Self
&mut self <=> self: &mut Self
// self 会拿走当前结构体实例(调用对象)的所有权,而 &self 却只会借用一个不可变引用,&mut self 会借用一个可变引用
struct Rectangle {
    p1: Point,
    p2: Point,
}
impl Rectangle {
    // 这是一个方法
    // `&self` 是 `self: &Self` 的语法糖
    // `Self` 是当前调用对象的类型,对于本例来说 `Self` = `Rectangle`
    fn perimeter(&self) -> f64 {
        let Point { x: x1, y: y1 } = self.p1;
        let Point { x: x2, y: y2 } = self.p2;

        2.0 * ((x1 - x2).abs() + (y1 - y2).abs())
    }
}

以self声明的方法会拿走调用者的所有权

关联函数使用 :: 操作符来调用

fn main() {
    let rectangle = Rectangle {
        // 关联函数的调用不是通过点操作符,而是使用 `::`
        p1: Point::origin(),
        p2: Point::new(3.0, 4.0),
    };
}

方法使用 . 操作符调用

println!("Rectangle perimeter: {}", rectangle.perimeter());

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

impl Rectangle {
    // 完成 area 方法,返回矩形 Rectangle 的面积
    // fn area
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };

    assert_eq!(rect1.area(), 1500);
}

// 只填空,不要删除任何代码行!
#[derive(Debug)]
struct TrafficLight {
    color: String,
}

impl TrafficLight {
    pub fn show_state(&self)  { // 如果这里使用 self 而不是 &self,就会拿走所有权
        println!("the current state is {}", self.color);
    }
}
fn main() {
    let light = TrafficLight{
        color: "red".to_owned(),
    };
    // 不要拿走 `light` 的所有权
    light.show_state();
    // 否则下面代码会报错
    println!("{:?}", light);
}
0

评论 (0)

取消