Skip to content

rust记忆点3

Published: at 22:23

结构体

结构体像是TypeScript中的 Interface,在大括号中定义每一部分数据的名字和类型

struct User {
  active: bool,
  username: String,
  email: String,
  sign_in_count: u64
}

解构赋值

Javascript类似,Rust可以使用解构赋值,如下

fn main() {
    // --snip--

    let user2 = User {
        email: String::from("another@example.com"),
        ..user1
    };
}

不同的是,Rust使用..来解构

没有命名字段的元组结构体

与之前不同,可以创建没有字段的结构体,如下

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

fn main() {
    let black = Color(0, 0, 0);
    let origin = Point(0, 0, 0);
}

没有任何字段的类单元结构体

常用在想要在某个类型上实现trait但不需要在类型中存储数据的时候。

struct AlwaysEqual;

fn main() {
    let subject = AlwaysEqual;
}

方法

方法和函数类似,都是用fn关键字和名称声明,可以拥有参数和返回值。不同的是方法在结构体的上下文中被定义(或者是枚举或 trait 对象的上下文), 并且他们第一个参数就是self,代表调用该方法的结构体实例。

方法就相当于JavaScript中的Class中声明的方法,可以在实例化Class后调用。

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