-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRust Basics.txt
283 lines (188 loc) · 7.23 KB
/
Rust Basics.txt
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
Rust Basics
Project Setup
------------------
For Rust projects, a workspace is a container project which holds other projects. The benefit of the workspace structure is that it enables us to manage multiple projects as one unit. It also helps to store all related projects seamlessly within a single git repo.
cargo new --bin <project-name> // creates a new empty top level binary application
cargo new <subproject-name> // creates a subproject within a workspace
// Cargo.toml - Top Level
// specifies the relationship between the subprojects
[workspace]
members = [
"tcpserver", "tcpclient", "http", "httpserver"
]
cargo run // runs program and outputs all statements in the code
cargp run -p tcpserver // runs the subproject/package tcpserver
carge run --release // runs program and ignores debug asserstions
cargo run --verbose // see what cargo passes to rustc
Variables
-------------
In Rust, by default variables are immutable
fn main() {
let x = 5;
println!("The value of x is: {}", x);
}
To let the compiler know that I want a variable to be mutable I must preface it with "mut"
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}
Integers
-----------
Strings and String Slices (&str)
-----------------------------------------
- by default all variables in Rust are immutable
- once a value is set to a name, I cannot change that value
Tuples
---------
Vectors
---------
Enums
---------
Hashmaps
---------------
Functions
--------------
defined in snake_case (e.g. fn another_function) not camelcase like in Javascript
types must be defined within parameter sets:
fn another_function(x: i32) {
println!("The value of x is: {}", x);
}
return types are defined with the -> syntax:
fn plus_one(x: i32) -> i32 {
x + 1
}
functions can return multiple values within a single tuple:
fn plus_one(x: i32) -> (method, version, resource) {
x + 1
}
Structs (Classes)
----------------------
Structs let you create custom types that are meaningful for your domain. By using structs, you can keep associated pieces of data connected to each other and name each piece to make your code clear. Methods let you specify the behavior that instances of your structs have, and associated functions let you namespace functionality that is particular to your struct without having an instance available.
// define the struct and it's fields/properties (like a class)
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
// create an instance of a struct
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
// update a field in an instance of a struct (if it's mutable)
let mut user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
user1.email = String::from("anotheremail@example.com"); // update
Note that the entire instance must be mutable; Rust doesn’t allow us to mark only certain fields as mutable; this is unlike java and c# where I can define what's public versus what is private
Adding Behavior to Structs -- Implementations
------------------------------------------------------------------
Adding methods to structs unleashes the full power of object oriented programing. Functions are not defined within the scope of the struct, but rather outside. This enables functions to be "associated" with a custom data type. This lose coupling of the data type from it's underlying behavior is quite powerful. In other languages (java, c#) with classes, we see methods (behavior) defined together with their properties (Composition).
struct Rectangle {
width: u32,
height: u32,
}
// associating a method to the Rectangle struct; impl means "implementation"
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area() // no semi-colon implies a return statement
);
}
[Creating New Instances of Custom Data Types]
- in Rust there is no concept of a default constructor; it is best to define a "new" impl to handle this for you
struct Person {
name: String,
age: u8
}
impl Person {
fn new(name: String, age: u8) -> Self {
Self { // implicitly returning a new Person (Self) struct
name: name
age: age
}
}
}
[Understanding Self and &self]
- Associated functions do not take &self as a paramater and are called with double-colons ::
- Methods take &self (an instance of the data type) and are called with . notation. These are typically used to conduct internal operations on the custom data type itself
// Associated Function (&self not used as a parameter)
impl Question {
fn new(id: QuestionId, title: String, content: String, tags: Option<Vec<String>>) -> Self {
Question {
id,
title,
content,
tags
}
}
// Method (takes &self as a parameter)
fn update_title(&self, id: QuestionId, new_title: String) -> Self {
self.update_question (id, new_title)
}
}
Bundling Common Functionality -- Traits
----------------------------------------------------
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {:?}", rect1);
}
Putting the specifier {:?} or {:#?} inside the curly brackets tells println! we want to use an output format called Debug. The Debug trait enables us to print our struct in a way that is useful for developers so we can see its value while we’re debugging our code.
Rust has provided a number of traits for us to use with the derive annotation that can add useful behavior to our custom types.
Wrapping & Unwrapping
--------------------------------
References & Borrowing (& syntax)
----------------------------------------------
The "&" allows me to reference a value without taking ownership of it. When we "borrow" in this fashion, the value that we are borrowing is immutable and therefore cannot be changed
BEFORE:
fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("The length of '{}' is {}.", s2, len);
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len(); // len() returns the length of a String
(s, length)
}
AFTER:
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1); // using a reference
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize { // a reference to a "string" in parameter set
s.len()
}
In order to make a reference mutable (changeable) we simply preface with "mut":
fn main() {
let mut s = String::from("hello");
change(&mut s); // add &mut
}
fn change(some_string: &mut String) { // add &mut; this is a mutable reference
some_string.push_str(", world");
}