feat: Add exercises for understanding borrowing

Exercises to explore immutable borrowing, mutable borrowing, and "aliasing xor mutability".
This commit is contained in:
James Gill 2021-10-26 08:07:51 -04:00
parent af91eb508a
commit b7c5165757
4 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,18 @@
// borrowing1.rs
// If you want to let a function borrow a variable but not move it,
// you can use references. This allows you to use the variable later.
// Make this compile without cloning `hello`.
// I AM NOT DONE
fn main() {
let hello = String::from("Hello world!");
let length = string_size(hello);
println!("The string `{}` has {} characters", hello, length);
}
fn string_size(s: String) -> usize {
s.len()
}

View File

@ -0,0 +1,18 @@
// borrowing2.rs
//
// Rust has strong guarantees about immutability. In order for something
// to be mutated, it must be marked explicitly. Make this compile only
// by changing the mutabilities of the calls.
// I AM NOT DONE
fn main() {
let hello = String::from("Hello ");
append_world(&hello);
assert_eq!(&hello, "Hello world!");
}
fn append_world(s: &String) {
s.push_str("world!");
}

View File

@ -0,0 +1,18 @@
// borrowing3.rs
//
// A core safety feature of Rust is that it may not have mutable and immutable
// borrows. Make this compile only by changing the order of the lines.
// I AM NOT DONE
fn main() {
let mut hello = String::from("Hello ");
let hello_ref = &hello;
append_world(&mut hello);
println!("{}", hello_ref);
}
fn append_world(s: &mut String) {
s.push_str("world!");
}

View File

@ -453,6 +453,45 @@ path = "exercises/quiz2.rs"
mode = "compile"
hint = "No hints this time ;)"
# BORROWING
[[exercises]]
name = "borrowing1"
path = "exercises/borrowing/borrowing1.rs"
mode = "compile"
hint = """
To let a function borrow a variable, you must use a reference.
Have a look in The Book, to find out more:
https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
"""
[[exercises]]
name = "borrowing2"
path = "exercises/borrowing/borrowing2.rs"
mode = "compile"
hint = """
In order for a variable to be mutated, it must be declared mutable.
In order for a borrowed variable to mutated, it must be a mutable reference.
Have a look in The Book, to find out more:
https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
"""
[[exercises]]
name = "borrowing3"
path = "exercises/borrowing/borrowing3.rs"
mode = "compile"
hint = """
Rust won't let you have multiple mutable borrows. You can either have
one mutable borrow, or multiple immutable borrows.
Have a look in The Book, to find out more:
https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
"""
# ERROR HANDLING
[[exercises]]