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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
fn main() {
let value: i8 = -1;
println!("i8: {}", value);

let value: i32 = -10000;
println!("i32: {}", value);

let value: i64 = -10001;
println!("i64: {}", value);

let value: isize = -10002;
println!("isize: {}", value);

let value: u8 = 3;
println!("u8: {}", value);

let value: u32 = 10004;
println!("u32: {}", value);

let value: u64 = 10005;
println!("u64: {}", value);

let value: usize = 10006;
println!("usize: {}", value);

let value = 92_222;
println!("i32_: {}", value);

let value = 0xfff;
println!("i32_十六进制: {}", value);

let value = 0o77;
println!("i32_八进制: {}", value);

let value = 0b1111_0000;
println!("i32_二进制: {}", value);

let value = b'A';
println!("b'A': {}", value);

let value: f64 = 2.0;
println!("f64: {}", value);

let value: f32 = 3.0;
println!("f32: {}", value);

let value: bool = true;
println!("bool: {}", value);

let value: char = 'Z';
println!("char: {}", value);

let value: (i32, bool) = (1, true);
println!("元组 {:?}", value);

let value1 = value.0;
println!("value1: {}", value1);

let value2 = value.1;
println!("value2: {}", value2);

let (value, value_b) = value;
println!("new value_1: {}", value);
println!("new value_b: {}", value_b);

let value: [i32; 3] = [1, 2, 3];
println!("new value_2: {:?}", value);

let value = [3; 3]; // [3, 3, 3]
println!("new value_3: {:?}", value);


let value3 = value[0];
println!("value3: {}", value3);
}

输出:

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
i8: -1
i32: -10000
i64: -10001
isize: -10002
u8: 3
u32: 10004
u64: 10005
usize: 10006
i32_: 92222
i32_十六进制: 4095
i32_八进制: 63
i32_二进制: 240
b'A': 65
f64: 2
f32: 3
bool: true
char: Z
元组 (1, true)
value1: 1
value2: true
new value_1: 1
new value_b: true
new value_2: [1, 2, 3]
new value_3: [3, 3, 3]
value3: 3



循环


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
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};

println!("result: {}", result);
println!("while之前的counter值为: {}", counter);

while counter > 0 {
println!("counter: {}", counter);
counter -= 1;
}

println!("-------------------");


let elements = [1, 2];
for element in elements.iter() {
println!("element: {}", element);
}

println!("-------------------");


for number in (0..4).rev() {
println!("number: {}", number);
}

println!("123")
}

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
result: 20
while之前的counter值为: 10
counter: 10
counter: 9
counter: 8
counter: 7
counter: 6
counter: 5
counter: 4
counter: 3
counter: 2
counter: 1
-------------------
element: 1
element: 2
-------------------
number: 3
number: 2
number: 1
number: 0
123



结构体嵌套


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
fn main() {
let user1 = User {
username: String::from("someone"),
email: String::from("someone@qq.com"),
};

let user2 = User {
username: user1.username,
..user1
};


println!("user2: {:?}", user2);
println!("调用build_user: {:?}", build_user(String::from("shuang"), String::from("i@dashen.tech")));
}

fn build_user(username: String, email: String) -> User {
return User {
username,
email,
};
}


#[derive(Debug)] // 必须要加,不然`User` doesn't implement `Debug` (required by {:?})
struct User {
username: String,
email: String,
}
1
#[derive(Debug)] 这个`derive` 属性会自动创建所需的实现,使限定的`struct` 能使用 `fmt::Debug` 打印

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
warning: field is never read: `email`
--> src/main.rs:28:5
|
28 | email: String,
| ^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
note: `User` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
--> src/main.rs:25:10
|
25 | #[derive(Debug)]
| ^^^^^
= note: this warning originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info)

warning: `error` (bin "error") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.55s
Running `target/debug/error`
user2: User { username: "someone", email: "someone@qq.com" }
调用build_user: User { username: "shuang", email: "i@dashen.tech" }

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
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}

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

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

impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width == other.width && self.height == other.height
}
}

fn main() {
let rect = Rectangle { width: 30, height: 30 };
println!("rect {:?} area {:?}", rect, rect.area());
}

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
warning: associated function is never used: `square`
--> src/main.rs:12:8
|
12 | fn square(size: u32) -> Rectangle {
| ^^^^^^
|
= note: `#[warn(dead_code)]` on by default

warning: associated function is never used: `can_hold`
--> src/main.rs:18:8
|
18 | fn can_hold(&self, other: &Rectangle) -> bool {
| ^^^^^^^^

warning: `error` (bin "error") generated 2 warnings
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/error`
rect Rectangle { width: 30, height: 30 } area 900



枚举及结构体


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

#[derive(Debug)]
enum IpAddrKind {
V4,
V6,
}

#[derive(Debug)]
struct IpAddr {
kind: IpAddrKind,
address: String,
}

fn main() {
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1"),
};

let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from("::1"),
};

println!("home: {:?}", home);
println!("loopback: {:?}", loopback);
}

输出:

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
warning: field is never read: `kind`
--> src/main.rs:10:5
|
10 | kind: IpAddrKind,
| ^^^^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
note: `IpAddr` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
--> src/main.rs:8:10
|
8 | #[derive(Debug)]
| ^^^^^
= note: this warning originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info)

warning: field is never read: `address`
--> src/main.rs:11:5
|
11 | address: String,
| ^^^^^^^^^^^^^^^
|
note: `IpAddr` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
--> src/main.rs:8:10
|
8 | #[derive(Debug)]
| ^^^^^
= note: this warning originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info)

warning: `error` (bin "error") generated 2 warnings
Finished dev [unoptimized + debuginfo] target(s) in 0.69s
Running `target/debug/error`
home: IpAddr { kind: V4, address: "127.0.0.1" }
loopback: IpAddr { kind: V6, address: "::1" }

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
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}


struct QuitMessage;

// unit struct
struct MoveMessage {
x: i32,
y: i32,
}

struct WriteMessage(String);

// tuple struct
struct ChangeColorMessage(i32, i32, i32); // tuple struct


impl Message {
fn call(&self) {
// method body would be defined here
}
}


fn main() {
let m = Message::Write(String::from("hello"));
m.call();
}

输出:

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
42
43
44
45
46
47
warning: variant is never constructed: `Quit`
--> src/main.rs:2:5
|
2 | Quit,
| ^^^^
|
= note: `#[warn(dead_code)]` on by default

warning: variant is never constructed: `Move`
--> src/main.rs:3:5
|
3 | Move { x: i32, y: i32 },
| ^^^^^^^^^^^^^^^^^^^^^^^

warning: variant is never constructed: `ChangeColor`
--> src/main.rs:5:5
|
5 | ChangeColor(i32, i32, i32),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^

warning: struct is never constructed: `QuitMessage`
--> src/main.rs:9:8
|
9 | struct QuitMessage;
| ^^^^^^^^^^^

warning: struct is never constructed: `MoveMessage`
--> src/main.rs:12:8
|
12 | struct MoveMessage {
| ^^^^^^^^^^^

warning: struct is never constructed: `WriteMessage`
--> src/main.rs:17:8
|
17 | struct WriteMessage(String);
| ^^^^^^^^^^^^

warning: struct is never constructed: `ChangeColorMessage`
--> src/main.rs:20:8
|
20 | struct ChangeColorMessage(i32, i32, i32); // tuple struct
| ^^^^^^^^^^^^^^^^^^

warning: `error` (bin "error") generated 7 warnings
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/error`



if let


1
2
3
4
5
6
7
8
9
10
11
12
13
fn main() {
let some_u8_value = Some(3);
match some_u8_value {
Some(3) => println!("Three"),
_ => ()
}

if let Some(4) = some_u8_value {
println!("Three!");
} else {
println!("No match!");
}
}

输出:

1
2
Three
No match!



Vec


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fn main() {
let mut v: Vec<i32> = Vec::new();
let mut v = vec![1, 2, 3, 4, 5];

v.push(5);

let third: &i32 = &v[2];
println!("The third element is {}", third);

match v.get(2) {
Some(third) => println!("The third element is {}", third),
None => println!("There is no third element."),
}

//let does_not_exist = &v[100];
let does_not_exist = v.get(100); // 不会报错正常返回None
println!("does_not_exist: {:?}", does_not_exist);
}

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
warning: unused variable: `v`
--> src/main.rs:2:13
|
2 | let mut v: Vec<i32> = Vec::new();
| ^ help: if this is intentional, prefix it with an underscore: `_v`
|
= note: `#[warn(unused_variables)]` on by default

warning: variable does not need to be mutable
--> src/main.rs:2:9
|
2 | let mut v: Vec<i32> = Vec::new();
| ----^
| |
| help: remove this `mut`
|
= note: `#[warn(unused_mut)]` on by default

warning: `error` (bin "error") generated 2 warnings
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/error`
The third element is 3
The third element is 3
does_not_exist: None



String


1
2
3
4
5
6
7
8
9
10
11
12
13
fn main() {
let mut s = String::new();

let data = "initial contents";
let s = data.to_string();

// the method also works on a literal directly:
let s = "initial contents".to_string();

let s1 = String::from("Hello, ");
let s2 = String::from("world!");
println!("s2 {} s1 {}", s2, s1);
}

输出:

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
warning: unused variable: `s`
--> src/main.rs:2:13
|
2 | let mut s = String::new();
| ^ help: if this is intentional, prefix it with an underscore: `_s`
|
= note: `#[warn(unused_variables)]` on by default

warning: unused variable: `s`
--> src/main.rs:5:9
|
5 | let s = data.to_string();
| ^ help: if this is intentional, prefix it with an underscore: `_s`

warning: unused variable: `s`
--> src/main.rs:8:9
|
8 | let s = "initial contents".to_string();
| ^ help: if this is intentional, prefix it with an underscore: `_s`

warning: variable does not need to be mutable
--> src/main.rs:2:9
|
2 | let mut s = String::new();
| ----^
| |
| help: remove this `mut`
|
= note: `#[warn(unused_mut)]` on by default

warning: `error` (bin "error") generated 4 warnings
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/error`
s2 world! s1 Hello,



HashMap


1
2
3
4
5
6
7
8
9
10
11
12
use std::collections::HashMap;

fn main() {
let text = "hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}

println!("{:?}", map);
}

输出:

1
{"world": 2, "wonderful": 1, "hello": 1}