Custom Types

Rust中有两种自定义类型

  • struct
  • enum

struct

在结构体中,有三种struct的类型,分别为

  • 元祖数据结构
  • 类C struct
  • unit struts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#[derive(Debug)]
struct Person<'a> {
    // 'a 表示生命周期,当Person生命结束了,那么name也结束了。
    name: &'a str,
    age: u8,
}

struct Nil;

struct Pair(i32, f32);

struct Point {
    x: f32,
    y: f32,
}


// 取消禁用代码警告
#[allow(dead_code)]
struct Rectangle {
    top_left: Point,
    bottom_right: Point,
}

fn main() {
    let name = "Peter";
    let age = 27;
    let peter = Person { name, age };

    let _nil = Nil;
    let pair = Pair(1, 0.1);

    let point1: Point = Point { x: 10.3, y: 0.4 };
    let point2 = Point { x: 5.2, y: point1.y };

    let _rectangle = Rectangle {
        top_left:point1,
        bottom_right: point2,
    };

}

enum

Rust中的枚举类型非常丰富,而且使用非常广泛。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
enum WebEvent {
    PageLoad,
    PageUnload,
    KeyPress(char),
    Paste(String),
    Click { x: i64, y: i64 },
}

fn inspect(event:WebEvent) {
    match event {
        WebEvent::PageLoad => println!("Page Load"),

        WebEvent::PageUnload => println!("page unloaded"),
        WebEvent::KeyPress(c) =>   println!("press {}", c),
        WebEvent::Paste(s) => println!("paste {}", s),
        WebEvent::Click { x,y} => {
            println!("clicked at x={}, y={}.", x, y);
        },
    }
}


fn main() {
    let press = WebEvent::KeyPress('c');
    inspect(press)

}

可以看到,枚举可以带参数。

type重命名

1
2
3
4
5
enum VeryVerboseEnumOfThingsToDoWithNumbers {
    Add,
    Subtract,
}
type Operations = VeryVerboseEnumOfThingsToDoWithNumbers;

那么就可以使用Operations来代替VeryVerboseEnumOfThingsToDoWithNumbers

C-like struct

还可以定义类似于C那种的枚举类型

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
enum Number {
    Zero, // 0
    One,   // 1
    Two,   // 2
}

enum Color {
    Red = 0xff0000,
    Green = 0x00ff00,
    Blue = 0x0000ff,
}

fn main() {
    // `enums` can be cast as integers.
    println!("zero is {}", Number::Zero as i32);
    println!("one is {}", Number::One as i32);

    println!("roses are #{:06x}", Color::Red as i32);
    println!("violets are #{:06x}", Color::Blue as i32);
}

常量

Rust中有两种常量

  • const
  • static
1
2
static LANGUAGE: &str = "Rust";
const THRESHOLD: i32 = 10;

参考