IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    rust记忆点3

    Moxuy发表于 2023-10-12 14:33:32
    love 0

    结构体

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

    1
    2
    3
    4
    5
    6
    struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64
    }

    解构赋值

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

    1
    2
    3
    4
    5
    6
    7
    8
    fn main() {
    // --snip--

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

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

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

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

    1
    2
    3
    4
    5
    6
    7
    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但不需要在类型中存储数据的时候。

    1
    2
    3
    4
    5
    struct AlwaysEqual;

    fn main() {
    let subject = AlwaysEqual;
    }

    方法

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

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    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()
    );
    }


沪ICP备19023445号-2号
友情链接