forked from inancgumus/learnrust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
91 lines (78 loc) · 2.79 KB
/
main.rs
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// You can use a struct type (also an enum type) represent a concept, and organize similar data under a single umbrella.
// User is a struct type
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
fn main() {
// root is an instance of the User struct.
//
// to change the root instance, its entire instance
// should be declared as mutable.
let mut root = User {
username: String::from("guest"),
email: String::from("[email protected]"),
sign_in_count: 5,
active: false,
};
// change the username field
root.username = String::from("root");
println!("{}'s email: {}", root.username, root.email);
// ----------------------------------------------------------
let guest = build_user(String::from("guest"), String::from("[email protected]"));
let active = if guest.active { "active" } else { "not active" };
println!("{}'s email: {}", guest.username, guest.email);
println!("\t{} and signed on {} times.", active, guest.sign_in_count);
// ----------------------------------------------------------
let jack = User {
username: String::from("jack"),
email: String::from("[email protected]"),
// CUMBERSOME:
// active: root.active,
// sign_in_count: root.sign_in_count,
//
// STRUCT UPDATE SYNTAX:
..root
};
let active = if guest.active { "active" } else { "not active" };
println!("{}'s email: {}", jack.username, jack.email);
println!("\t{} and signed on {} times.", active, jack.sign_in_count);
// ----------------------------------------------------------
// TUPLE STRUCTS
// Example: struct Point(i32, i32);
// -> Have a type name: Point.
// -> Have fields : (i32, i32).
// -> Fields don't have names.
//
// When to use?
// -> To give the tuple a name to make it different from other types.
// -> When naming every other field a name is verbose and reduntant.
struct Color(i32, i32, i32); // (Red, Green, Blue)
struct Point(i32, i32, i32); // (X, Y, Z)
let mut _black = Color(0, 0, 0);
let mut _origin = Point(0, 0, 0);
// Each struct you define is its own type,
// even though the fields within the struct
// have the same types.
//
// _black = _origin // MISMATCHED TYPES:
// _black is a Color
// _origin is a Point
// You can access tuple struct fields using their indexes.
println!("R: {}, G: {}, B: {}", _black.0, _black.1, _black.2);
}
fn build_user(email: String, username: String) -> User {
User {
// CUMBERSOME:
// email: email,
// username: username,
//
// FIELD-INIT SHORTHAND:
email,
username,
sign_in_count: 1,
active: true,
}
}