-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasics.rs
More file actions
178 lines (134 loc) · 5.24 KB
/
basics.rs
File metadata and controls
178 lines (134 loc) · 5.24 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#![allow(dead_code, unused_variables)]
use std::fmt; // 'use' is 100% optional, fully qual. name can be used each time instead
use std::cmp::Ordering;
/* ----------------------------------
* ------- EXECUTE -------
* ----------------------------------
*/
pub fn run() {
basics();
debug_trait();
display_trait();
display_list();
primitives();
comparing_values();
}
// ############################
// ### SYNTAX & PRINT ###
// ############################
fn basics() {
let country = "Japan";
println!("Hello {}!", country);
println!("Hello {0}!", "Switzerland"); // Positional args
println!("Hello {country}!", country="Iceland"); // Named args
println!("0b{number:>8b}", number=42); // Right-justify(>), width=8
println!("0b{number:<8b}", number=11); // Left-justify (<) by pointing arrow left
println!("--{number:^12b}--", number=11); // Center-align (^), if uneven, more padding on right
println!("0b{number:0>8b}", number=42); // Syntax: {arg:fill direction width fmt_char}
println!("0x{number:f>width$x}", number=75, width=4); // Named args in format specifier by postfixing `$`.
}
fn debug_trait() {
#[derive(Debug)] // Automatic `fmt::Debug` impl.
struct Structure(i32, f32);
#[derive(Debug)]
struct Deep(Structure);
println!("{1} {0:?} is the {agent:?} name.", "Peter", "Burke", agent="agents's");
println!("{:?}", Deep(Structure(42, 3.141592)));
#[derive(Debug)]
struct Person<'a> {
name: &'a str,
age: u8
}
let name = "Peter Burke";
let age = 42;
let agent = Person { name, age };
println!("{:#?}", agent); // ':#?' pretty print, expanded version
}
fn display_trait() {
#[derive(Debug)]
struct Vector2D(i64, i64);
impl fmt::Display for Vector2D {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.0, self.1) // Use `self.number` to refer to each positional data point
}
}
impl fmt::Binary for Vector2D {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let magnitude = (self.0 * self.0 + self.1 * self.1) as f64;
let magnitude = magnitude.sqrt();
let decimals = f.precision().unwrap_or(3);
let string = format!("{magnitude:.decimals$}");
f.pad_integral(true, "", &string)
}
}
let range = Vector2D(-128, 127);
println!("Range: {range}\n"); // Implicitly displayed b/c fmt::Display impl.
let vector = Vector2D(0, 14);
println!("Binary: {:10.2b}", vector);
println!("Debug: {:?}\n", vector);
#[derive(Debug)]
struct Point2D{x: f64, y: f64}
impl fmt::Display for Point2D {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "x: {}, y: {}", self.x, self.y) // Referencing named fields
}
}
let point = Point2D{x: 3.3, y: 7.2};
println!("Display: {}", point);
println!("Debug: {:?}", point);
}
fn display_list() {
struct Pokemon { name: String, level: u8 }
impl fmt::Display for Pokemon {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Pokemon {{ name: {}, level: {} }}", self.name, self.level)
}
}
struct List(Vec<Pokemon>);
impl fmt::Display for List {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let vec = &self.0;
write!(f, "[")?;
for (i, ele) in vec.iter().enumerate() {
if i != 0 { write!(f, ", ")?; }
write!(f, "\n\t{i}: {}", ele)?;
}
write!(f, "\n]")
}
}
let v = List(vec![
Pokemon { name: String::from("Chikorita"), level: 15 },
Pokemon { name: String::from("Totodile"), level: 11 },
Pokemon { name: String::from("Cyndaquil"), level: 12 }
]);
println!("{}", v);
}
// ############################
// ### DATA TYPES ###
// ############################
fn primitives() {
let a: u8 = 42; // Sizes: 8, 16, 32, 64, 128 bits
let b: i16 = -42;
let c: f32 = 3.14;
let d: char = 'A'; // Unicode (utf-8)
let e: bool = true;
let array: [i32; 5] = [1, 2, 3, 4, 5];
let tuple: (i32, &'static str, f64) = (1, "Hello", 3.14);
println!("Tuple: {:?}", tuple);
let (t1, t2, t3) = tuple; // Destructuring
type Age = u8; // Type alias
type Point = (f64, f64); // Type alias for tuple
const PI: f64 = 3.141592; // Consts substituted in-line at compile time
static NAME: &str = "Rusty Pirate Ship"; // Statics stored in heap memory (single loc)
}
fn comparing_values() {
let val: u8 = 18;
let target = 42;
match val.cmp(&target) {
Ordering::Less => println!("Too small O_O"),
Ordering::Greater => println!("Too big ._."),
Ordering::Equal => {
println!("Match!");
}
}
}