走进 Rust:结构体方法

Rust About 1,117 words

方法语法

方法与函数相似:它们使用fn关键字及其名称进行声明,可以具有参数和返回值,并且包含一些在其他地方调用时运行的代码。但是,方法与函数的不同之处在于,它们是在结构体的上下文中定义的(或者是在enumtrait对象,分别在第6和17章中介绍),并且它们的第一个参数始终是self,它代表调用该方法的结构体实例。

定义方法

impl实现结构体,定义方法,方法的入参第一个参数必须是self(一般传递实例的引用&self,不然会被所有权drop导致后续代码无法使用该实例)。

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

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()
    );
}

相关函数

impl实现结构体中,如果该函数的入参没有该结构体的实例,则该函数不能称为方法。一般这样的函数是用来初始化该结构体的实例。如String::from

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

多个impl块

impl可以用来实现多次结构体,但定义的方法或函数不能同名,否则编译器会报duplicate definitions with name ...错误。

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

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}
Views: 2,127 · Posted: 2020-07-10

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh