struct

5 Struct

结构体是一个自定义的数据类型,允许你把一些相关的数据组合打包到一起,组成一个有意义的组。

define

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

instance

1
2
3
4
5
6
let user1 = User{
username: String::from("wutb"),
email: String::from("wutb@asiainfo.com")
sign_in_count: 1,
active: true,
}

create from other instance

1
2
3
4
5
let user2 = User{
username: String::from("lixu"),
email: String::from("lixu@qq.com"),
..user1
}

Tuple Struct without named fields

1
struct Color(i32, i32, i32);

method syntax

method(方法),与function(函数)非常相似,不同之处:

  1. 必须在struct的上下文中声明
  2. 第一个参数必须是self
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    #[derive(Debug)] // annotation
    struct Rectangle {
    width: u32,
    height: u32,
    }
    impl Rectangle {
    fn area(&self) -> u32 {
    self.width * self.height
    }
    }

associated function 关联函数

functions within impl blocks that don’t take self as a parameter.
调用关联函数时使用::标识符,例如, String::from()

Multiple impl Blocks

struct is allowed to have multiple impl blocks

© 2023 PLAYAROUND All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero