You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+278Lines changed: 278 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -9,3 +9,281 @@ cargo run --example iterator
9
9
```
10
10
11
11
#### You can learn about RUST coding from here.
12
+
13
+
# My_Learning-Rust
14
+
Rust programming language
15
+
16
+
## Installation
17
+
### Linux or MacOS
18
+
* Install
19
+
```console
20
+
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
21
+
```
22
+
23
+
* Update using `$ rustup update`
24
+
25
+
## Commands
26
+
* View installed version via `$ rustup show`
27
+
* Check latest version via `$ rustup check`
28
+
29
+
> Often, `cargo check` is much faster than `cargo build`, because it skips the step of producing an executable. If you’re continually checking your work while writing the code, using `cargo check` will speed up the process! As such, many Rustaceans run `cargo check` periodically as they write their program to make sure it compiles. Then they run `cargo build` when they’re ready to use the executable.
30
+
31
+
## Getting Started
32
+
### Code
33
+
```rs
34
+
fnmain() {
35
+
println!("Hello World!");
36
+
}
37
+
```
38
+
39
+
### Compile
40
+
```console
41
+
$ rustc hello.rs
42
+
```
43
+
44
+
### Output
45
+
```console
46
+
$ ./hello
47
+
```
48
+
49
+
## Concepts
50
+
51
+
*`..` used for range like `1..4` i.e. 1, 2, 3. But, if `1..=4` i.e. 1, 2, 3, 4
52
+
* There are different types of struct
53
+
* normal struct: with parameters
54
+
* unit struct: without parameters
55
+
56
+
> "Ownership is Rust’s most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector."
57
+
58
+
> <u>Borrow Checker</u>: You can move the data itself and give up ownership in the process, create a copy of the data and pass that along, or pass a reference to the data and retain ownership, letting the recipient borrow it for a while. The most appropriate approach depends entirely on the situation. Try [this](./tuts/functions/borrow_checker.rs)
59
+
60
+
> - Stack (fixed size like char, bool, int; less costly; quick to access by calling var like easy to copy the var) | Heap (variable size like string, list, class; more costly; access var or object via pointer)
61
+
62
+
* By default, all the variables are defined as `immutable` equivalent to `const` in JS/TS.
63
+
* In Rust, borrowing is analogous to referencing in C++ & dereferencing is same as that of C++.
64
+
* The value of mutable variable can be changed, but not the type.
65
+
* In Rust, every value has a single owner that determines its lifetime.
66
+
* The memory of the declared variables are dropped (or freed) when the program leaves a block in which the variable is declared.
67
+
- E.g. Normally, inside the `main` function, whenever a variable is defined, it is dropped after exiting the `main` function.
68
+
```rs
69
+
fnmain() {
70
+
// Case-1
71
+
letx=10;
72
+
letr=&x;
73
+
74
+
letk;
75
+
{
76
+
lety=Box::new(5); // Using Box pointer for storing into heap
77
+
lety=5; // stored in stack
78
+
// let y <'a> = 5;
79
+
// k = &y; // y dropped here as it is not available for lifetime. Moreover the block is getting over after this
80
+
k=y; // this implies that the ownership of 5 is transferred to `k` from `y`
81
+
}
82
+
}
83
+
```
84
+
* Rust doesn't allow _dangling pointer_ by design. This means that any variable, struct, enum, etc can't live more than the lifetime of the referenced type
85
+
```rs
86
+
structConfig {
87
+
88
+
}
89
+
90
+
// INCORRECT ❌
91
+
structApp {
92
+
config:&Config// `Config` used as reference
93
+
}
94
+
95
+
// CORRECT ✅
96
+
/// Here, it is used as lifetime ownership of the code.
97
+
structApp<'a> {
98
+
config:&'aConfig
99
+
}
100
+
```
101
+
*`lifetimes` are a compile-time feature and don’t exist at runtime.
102
+
* Rust memory safety is based on this rule: Given an object T, it is only possible to have one of the following:
103
+
- Having several immutable references (&T) to the object (also known as aliasing).
104
+
- Having one mutable reference (&mut T) to the object (also known as mutability).
105
+
* Apply `#[derive(Debug)]` for making the struct, enum printable
106
+
* Apply `#[derive(Clone)]` for making the struct, enum copyable.
107
+
*`Option` vs `Result`
108
+
109
+
| Option | Result |
110
+
|--|--|
111
+
| Some or None | Ok or Err |
112
+
| An optional value can have either Some value or no value/ None. | A result can represent either success/ Ok or failure/ Err
113
+
| The Option type is a way to use Rust’s type system to express the possibility of absence | Result expresses the possibility of error |
114
+
| mainly used for var, function output. For struct, the parameters can have Option type. E.g. In full name, middle_name can be missing for cases, so define `middle_name: Option<String>`| mainly used for operation, function. As normally a variable won't have Err unless there is some calculation involved with this var |
115
+
| Don't want to print the exact issue as `None` doesn't have anything as param unlike `Some(T)`| Want to print the exact issue as `Err(E)` contains the message inside |
116
+
| E.g. "./tuts/error_handling/opt" | E.g. "./tuts/error_handling/res" |
117
+
118
+
### Basics
119
+
#### Primitive types and Variables
120
+
1. Various sizes of integers, signed and unsigned (i32, u8, etc.)
121
+
1. Floating point types f32 and f64.
122
+
1. Booleans (bool)
123
+
1. Characters (char). Note these can represent unicode scalar values (i.e. beyond ASCII)
124
+
125
+
#### Print
126
+
*1. formatting variables inside `println` function
127
+
```
128
+
let name = "Abhijit";
129
+
let age = 28;
130
+
131
+
println!("My name is {name}, and age is {age}"); // ❌
132
+
println!("My name is {0}, and age is {1}", name, age); // ✔️
133
+
println!("My name is {}, and age is {}", name, age); // ✔️
134
+
```
135
+
*2. Multiple usage of variables without repetition
136
+
```
137
+
let alice = "Alice";
138
+
let bob = "Bob";
139
+
140
+
println!("{0}, this is {1}. {1}, this is {0}", alice, bob);
141
+
```
142
+
143
+
144
+
#### Variables
145
+
146
+
147
+
## Tools
148
+
* Check behind-the-code for a code snippet - https://play.rust-lang.org/
149
+
- Tools >> Expand Macros
150
+
151
+
## Troubleshoot
152
+
### 1. warning: path statement with no effect
153
+
*_Cause_: there is a statement having no effect
154
+
*_Solution_: Assign the variable to `_`.
155
+
156
+
Before:
157
+
```rs
158
+
letresult=matchgrade {
159
+
"A"=> { println!("Excellent!"); },
160
+
"B"=> { println!("Great!"); },
161
+
"C"=> { println!("Good"); },
162
+
"D"=> { println!("You passed"); },
163
+
"F"=> { println!("Sorry, you failed"); },
164
+
_=> { println!("Unknown Grade"); }
165
+
};
166
+
167
+
result;
168
+
```
169
+
170
+
After:
171
+
```rs
172
+
letresult=matchgrade {
173
+
"A"=> { println!("Excellent!"); },
174
+
"B"=> { println!("Great!"); },
175
+
"C"=> { println!("Good"); },
176
+
"D"=> { println!("You passed"); },
177
+
"F"=> { println!("Sorry, you failed"); },
178
+
_=> { println!("Unknown Grade"); }
179
+
};
180
+
181
+
// result; // warning: path statement with no effect, Solution --> assign to `_`
182
+
let_=result;
183
+
184
+
```
185
+
186
+
### 2. warning: variant is never constructed, error[E0277]: `UsState` doesn't implement `Debug`
187
+
*_Cause_: It simply means that the variant is never used, "constructed", anywhere in your program. There is no `AppAction::Task` anywhere in the program. Rust expects that if you say an enum variant exists, you will use it for something somewhere.
188
+
*_Solution_: by putting this before the enum, or individually before intentionally unused items, you can make the warning disappear:
189
+
190
+
Before:
191
+
```rs
192
+
enumUsState {
193
+
California,
194
+
Mexico,
195
+
Alaska,
196
+
}
197
+
198
+
enumCoin {
199
+
Penny,
200
+
Nickel,
201
+
Dime,
202
+
Quarter,
203
+
Custom(UsState),
204
+
}
205
+
```
206
+
207
+
After:
208
+
```rs
209
+
#[allow(dead_code)]
210
+
#[derive(Debug)] // this use is recommended, otherwise there is error.
211
+
enumUsState {
212
+
California,
213
+
Mexico,
214
+
Alaska,
215
+
}
216
+
217
+
#[allow(dead_code)]
218
+
enumCoin {
219
+
Penny,
220
+
Nickel,
221
+
Dime,
222
+
Quarter,
223
+
Custom(UsState),
224
+
}
225
+
```
226
+
227
+
### 3. Error: "move occurs...which does not implement the Copy trait"
228
+
*_Cause_: Copy designates types for which making a bitwise copy creates a valid instance without invalidating the original instance.
229
+
230
+
This isn't true for String, because String contains a pointer to the string data on the heap and assumes it has unique ownership of that data. When you drop a String, it deallocates the data on the heap. If you had made a bitwise copy of a String, then both instances would try to deallocate the same memory block, which is undefined behaviour.
231
+
232
+
*_Solution_: Just use `format` like this:
233
+
234
+
Before:
235
+
```rs
236
+
implDetailforCar {
237
+
fnbrand(&self) ->String {
238
+
returnself.brand;
239
+
}
240
+
fncolor(&self) ->String {
241
+
returnself.color;
242
+
}
243
+
}
244
+
```
245
+
246
+
After:
247
+
```rs
248
+
implDetailforCar {
249
+
fnbrand(&self) ->String {
250
+
// using `format` instead of directly returning the brand bcoz it throws error:
251
+
// "move occurs because `self.brand` has type `String`, which does not implement the `Copy` trait"
252
+
returnformat!("{}", self.brand);
253
+
}
254
+
fncolor(&self) ->String {
255
+
returnformat!("{}", self.color);
256
+
}
257
+
}
258
+
```
259
+
260
+
## References
261
+
*[Rust by example](https://doc.rust-lang.org/stable/rust-by-example/)
262
+
*[Book: The Rust Programming Language](https://doc.rust-lang.org/book/)
263
+
*[Rust for Haskell Programmers!](https://mmhaskell.com/rust)
*[Learn Rust by Book via Video](https://www.youtube.com/watch?v=5QsEuoIt7JQ&list=PLSbgTZYkscaoV8me47mKqSM6BBSZ73El6&index=1)
278
+
279
+
### Blogs
280
+
*[What is Rust and why is it so popular?](https://stackoverflow.blog/2020/01/20/what-is-rust-and-why-is-it-so-popular/)
281
+
*[Understanding the Rust borrow checker](https://blog.logrocket.com/introducing-the-rust-borrow-checker/)
282
+
*[No auto type deduction for function, but for local variable](https://stackoverflow.com/questions/24977365/differences-in-type-inference-for-closures-and-functions-in-rust)
283
+
*[Including Files and Deeply Directories in Rust](https://hackernoon.com/including-files-and-deeply-directories-in-rust-q35o3yer)
284
+
*[Understand Rust Ownership model by thoughtram](https://blog.thoughtram.io/rust/2015/05/11/rusts-ownership-model-for-javascript-developers.html)
285
+
*[Memory Safety in Rust: A Case Study with C](https://willcrichton.net/notes/rust-memory-safety/)
286
+
*[Ownership in Rust by thoughtram](https://blog.thoughtram.io/ownership-in-rust/)
287
+
*[References in Rust by thoughtram](https://blog.thoughtram.io/references-in-rust/)
288
+
*[Iterators in Rust by thoughtram](https://blog.thoughtram.io/iterators-in-rust/)
289
+
*[Lifetimes in Rust by thoughram](https://blog.thoughtram.io/lifetimes-in-rust/)
0 commit comments