No error happens, because [0] and [1] and [2] are all inside. But maybe it was important to only have three things. So we should have done this:
No error happens, because [0] and [1] and [2] are all inside. But maybe it was important to only have three things. So we should have done this:
```
```rust
fn main() {
fn main() {
let my_vec = vec![8, 9, 10];
let my_vec = vec![8, 9, 10];
prints_three_things(my_vec);
prints_three_things(my_vec);
@ -3271,17 +3265,17 @@ fn main() {
This is okay, but we don't want to print "The dog is running". We can change the method .run(), but we have to follow the signature. The signature says:
This is okay, but we don't want to print "The dog is running". We can change the method .run(), but we have to follow the signature. The signature says:
```rust
```rust
fn run(&self) {
fn run(&self) {
println!("The dog is running!");
println!("The dog is running!");
}
}
```
```
The signature says "fn run() takes &self, and returns nothing". So you can't do this:
The signature says "fn run() takes &self, and returns nothing". So you can't do this:
```rust
```rust
fn run(&self) -> i32 {
fn run(&self) -> i32 {
5
5
}
}
```
```
Rust will say:
Rust will say:
@ -3648,7 +3642,6 @@ fn main() {
assert_eq!(my_vec_iter.next(), Some(&'柳')); // Again
assert_eq!(my_vec_iter.next(), Some(&'柳')); // Again
assert_eq!(my_vec_iter.next(), None); // Nothing is left: just None
assert_eq!(my_vec_iter.next(), None); // Nothing is left: just None
assert_eq!(my_vec_iter.next(), None); // You can keep calling .next() but it will always be None
assert_eq!(my_vec_iter.next(), None); // You can keep calling .next() but it will always be None
}
}
```
```
@ -3695,9 +3688,9 @@ fn main() {
That works well. Now we want to implement ```Iterator``` for the library so we can use it in a ```for``` loop. Right now if we try a ```for``` loop, it doesn't work:
That works well. Now we want to implement ```Iterator``` for the library so we can use it in a ```for``` loop. Right now if we try a ```for``` loop, it doesn't work:
```rust
```rust
for item in my_library {
for item in my_library {
println!("{}", item);
println!("{}", item);
}
}
```
```
It says:
It says:
@ -3830,6 +3823,7 @@ fn main() {
my_closure(5);
my_closure(5);
}
}
```
```
When the closure becomes more complicated, you can add a code block. Then it can be as long as you want.
When the closure becomes more complicated, you can add a code block. Then it can be as long as you want.
```rust
```rust
@ -4019,10 +4013,8 @@ dbg!() is a very useful macro that prints quick information. Sometimes you use i
```rust
```rust
fn main() {
fn main() {
let my_number = 8;
let my_number = 8;
dbg!(my_number);
dbg!(my_number);
}
}
```
```
@ -4032,14 +4024,12 @@ But actually, you can put ```dbg!``` in many other places. Look at this code for
```rust
```rust
fn main() {
fn main() {
let mut my_number = 9;
let mut my_number = 9;
my_number += 10;
my_number += 10;
let new_vec = vec![8, 9, 10];
let new_vec = vec![8, 9, 10];
let double_vec = new_vec.iter().map(|x| x * 2).collect::<Vec<i32>>();
let double_vec = new_vec.iter().map(|x| x * 2).collect::<Vec<i32>>();
}
}
```
```
@ -4047,7 +4037,6 @@ This code creates a new mutable number and changes it. Then it creates a vec, an
```rust
```rust
fn main() {
fn main() {
let mut my_number = dbg!(9);
let mut my_number = dbg!(9);
dbg!(my_number += 10);
dbg!(my_number += 10);
@ -4056,25 +4045,24 @@ fn main() {
let double_vec = dbg!(new_vec.iter().map(|x| x * 2).collect::<Vec<i32>>());
let double_vec = dbg!(new_vec.iter().map(|x| x * 2).collect::<Vec<i32>>());
dbg!(double_vec);
dbg!(double_vec);
}
}
```
```
So this prints:
So this prints:
```rust
```
[src\main.rs:3] 9 = 9
[src\main.rs:3] 9 = 9
```
```
and:
and:
```rust
```
[src\main.rs:4] my_number += 10 = ()
[src\main.rs:4] my_number += 10 = ()
```
```
and:
and:
```rust
```
[src\main.rs:6] vec![8, 9, 10] = [
[src\main.rs:6] vec![8, 9, 10] = [
8,
8,
9,
9,
@ -4084,7 +4072,7 @@ and:
and:
and:
```rust
```
[src\main.rs:8] new_vec.iter().map(|x| x * 2).collect::<Vec<i32>>() = [
[src\main.rs:8] new_vec.iter().map(|x| x * 2).collect::<Vec<i32>>() = [
16,
16,
18,
18,
@ -4094,7 +4082,7 @@ and:
and:
and:
```rust
```
[src\main.rs:10] double_vec = [
[src\main.rs:10] double_vec = [
16,
16,
18,
18,
@ -4107,14 +4095,12 @@ and:
```rust
```rust
fn main() {
fn main() {
let new_vec = vec![8, 9, 10];
let new_vec = vec![8, 9, 10];
let double_vec = new_vec
let double_vec = new_vec
.iter()
.iter()
.map(|x| x * 2)
.map(|x| x * 2)
.collect::<Vec<i32>>();
.collect::<Vec<i32>>();
}
}
```
```
@ -4122,7 +4108,6 @@ We want to know more information about what the code is doing. So we add ```insp
```rust
```rust
fn main() {
fn main() {
let new_vec = vec![8, 9, 10];
let new_vec = vec![8, 9, 10];
let double_vec = new_vec
let double_vec = new_vec
@ -4131,7 +4116,6 @@ fn main() {
.map(|x| x * 2)
.map(|x| x * 2)
.inspect(|next_item| println!("Then it is: {}", next_item))
.inspect(|next_item| println!("Then it is: {}", next_item))
.collect::<Vec<i32>>();
.collect::<Vec<i32>>();
}
}
```
```
@ -4525,8 +4509,8 @@ There are many methods for ```RefCell```. Two of them are ```.borrow()``` and ``
So changing the value in a ```RefCell``` is very easy:
So changing the value in a ```RefCell``` is very easy:
```rust
```rust
user_1.active.replace(false);
user_1.active.replace(false);
println!("{:?}", user_1.active);
println!("{:?}", user_1.active);
```
```
And there are many other methods like ```replace_with``` that uses a closure:
And there are many other methods like ```replace_with``` that uses a closure:
@ -4569,7 +4553,7 @@ fn main() {
But if you run it, it will immediately panic.
But if you run it, it will immediately panic.
```rust
```
thread 'main' panicked at 'already borrowed: BorrowMutError', C:\Users\mithr\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\src\libcore\cell.rs:877:9
thread 'main' panicked at 'already borrowed: BorrowMutError', C:\Users\mithr\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\src\libcore\cell.rs:877:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\rust_book.exe` (exit code: 101)
error: process didn't exit successfully: `target\debug\rust_book.exe` (exit code: 101)
@ -5272,14 +5256,13 @@ fn main() {
std::thread::spawn(|| {
std::thread::spawn(|| {
println!("I am printing something");
println!("I am printing something");
});
});
// Now the threads start.
} // Now the threads start.
}
} // How many can finish before main() ends here?
} // How many can finish before main() ends here?
```
```
Usually about four threads will print before ```main``` ends, but it is always different. Also, sometimes the threads will panic:
Usually about four threads will print before ```main``` ends, but it is always different. Also, sometimes the threads will panic:
```rust
```
thread 'thread 'I am printing something
thread 'thread 'I am printing something
thread '<unnamed><unnamed>thread '' panicked at '<unnamed>I am printing something
thread '<unnamed><unnamed>thread '' panicked at '<unnamed>I am printing something
' panicked at 'thread '<unnamed>cannot access stdout during shutdown' panicked at '<unnamed>thread 'cannot access stdout during
' panicked at 'thread '<unnamed>cannot access stdout during shutdown' panicked at '<unnamed>thread 'cannot access stdout during
@ -5341,7 +5324,6 @@ Here is an example:
```rust
```rust
fn main() {
fn main() {
let my_string = String::from("I will go into the closure");
let my_string = String::from("I will go into the closure");
let my_closure = || println!("{}", my_string);
let my_closure = || println!("{}", my_string);
my_closure();
my_closure();
@ -5356,7 +5338,6 @@ If we change ```my_string```, it will be ```FnMut```.
```rust
```rust
fn main() {
fn main() {
let mut my_string = String::from("I will go into the closure");
let mut my_string = String::from("I will go into the closure");
let mut my_closure = || {
let mut my_closure = || {
my_string.push_str(" now");
my_string.push_str(" now");
@ -5377,7 +5358,6 @@ And if you take by value, then it will be FnOnce.
```rust
```rust
fn main() {
fn main() {
let my_vec: Vec<i32> = vec![8, 9, 10];
let my_vec: Vec<i32> = vec![8, 9, 10];
let my_closure = || {
let my_closure = || {
my_vec
my_vec
@ -5485,14 +5465,14 @@ So just remember: if you need a value in a thread from outside the thread, you n
You remember that we used an ```Rc``` to give a variable more than one owner. If we are doing the same thing in a thread, we need an ```Arc```. ```Arc``` means "atomic reference counter". Atomic means that it uses the computer's processor so that data only gets written once each time. This is important because if two threads write data at the same time, you will get the wrong result. For example, imagine if you could do this in Rust:
You remember that we used an ```Rc``` to give a variable more than one owner. If we are doing the same thing in a thread, we need an ```Arc```. ```Arc``` means "atomic reference counter". Atomic means that it uses the computer's processor so that data only gets written once each time. This is important because if two threads write data at the same time, you will get the wrong result. For example, imagine if you could do this in Rust:
```rust
```rust
let mut x = 10;
let mut x = 10;
for i in 0..10 { // Thread 1
for i in 0..10 { // Thread 1
x += 1
x += 1
}
}
for i in 0..10 { // Thread 2
for i in 0..10 { // Thread 2
x += 1
x += 1
}
}
```
```
If Thread 1 and Thread 2 just start together, maybe this will happen:
If Thread 1 and Thread 2 just start together, maybe this will happen:
@ -5569,10 +5549,10 @@ let my_number = Arc::new(Mutex::new(0));
Now that we have this, we can clone it. Each clone can go into a different thread. We have two threads, so we will make two clones:
Now that we have this, we can clone it. Each clone can go into a different thread. We have two threads, so we will make two clones:
```rust
```rust
let my_number = Arc::new(Mutex::new(0));
let my_number = Arc::new(Mutex::new(0));
let my_number1 = Arc::clone(&my_number); // This clone goes into Thread 1
let my_number1 = Arc::clone(&my_number); // This clone goes into Thread 1
let my_number2 = Arc::clone(&my_number); // This clone goes into Thread 2
let my_number2 = Arc::clone(&my_number); // This clone goes into Thread 2
```
```
Now that we have safe clones attached to ```my_number```, we can ```move``` them into other threads with no problem.
Now that we have safe clones attached to ```my_number```, we can ```move``` them into other threads with no problem.
Okay, so you put a number in and it gives you a ```String```. That's easy, but maybe you are curious. If you click on [src] you can see this:
Okay, so you put a number in and it gives you a ```String```. That's easy, but maybe you are curious. If you click on [src] you can see this:
```rust
```rust
pub fn with_capacity(capacity: usize) -> String {
pub fn with_capacity(capacity: usize) -> String {
String { vec: Vec::with_capacity(capacity) }
String { vec: Vec::with_capacity(capacity) }
}
}
```
```
Interesting! Now you can see that a String is a kind of ```Vec```. And actually a ```String``` is a vector of ```u8``` bytes, which is interesting to know. But you don't need to know that to use the ```with_capacity``` method so you only see it if you click [src]. So clicking on [src] is a good idea if the document doesn't have much detail and you want to know more.
Interesting! Now you can see that a String is a kind of ```Vec```. And actually a ```String``` is a vector of ```u8``` bytes, which is interesting to know. But you don't need to know that to use the ```with_capacity``` method so you only see it if you click [src]. So clicking on [src] is a good idea if the document doesn't have much detail and you want to know more.