DigestedSet

There's nothing actually digested.

0%

一天学一个rust语法[3] structure

Rust 支持结构体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}

fn build_user(email: String, username: String) -> User {
User {
active: true,
username,
email,
sign_in_count: 1,
}
}

比较神奇的是支持 spread operator:

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

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

以及 tuple structure:

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

如果需要打印 structure 结构,rust 提供了方便的方式,不过打印的时候要使用 {:?} 做占位符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}

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

println!("rect1 is {:?}", rect1);
}

实现方法的办法有点像 go,语法有点像 python,this 指针用的是&self

1
2
3
4
5
6
7
8
9
10
11
12
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
}
}

另外还有类似于 C++的静态方法的 associated functions

1
2
3
4
5
6
7
8
9
10

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