Skip to content

结构体

定义

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#[derive(Debug)] // 友好打印
struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}
fn main(){
    let user1 = User {
        email: String::from("[email protected]"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    }; // 注意这里user1在堆中

    dbg!(&rect1);
    println!("rect1 is {:?}", rect1); // 打印
    println!("rect1 is {:#?}", rect1); // 格式化打印
}
1
2
3
struct Color(i32, i32, i32);

let black = Color(0, 0, 0);

定义方法

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

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

Rust 自动解引用, 下面两句话相等.

1
2
p1.distance(&p2);
(&p1).distance(&p2);

可以不带self:

1
2
3
4
5
impl Rectangle {
    fn square(size: u32) -> Rectangle {
        Rectangle { width: size, height: size }
    }
}