Reference and Borrowing

Reference

  1. 🌟
2. fn main() {
3. let x = 5;
4. // Fill the blank
5. let p = __;

7. println!("the memory address of x is {:p}", p); // One possible output: 0x16fa3ac84
8. }
  1. 🌟
2. fn main() {
3. let x = 5;
4. let y = &x;

6. // Modify this line only
7. assert_eq!(5, y);

9. println!("Success!");
10. }
  1. 🌟
2. // Fix error
3. fn main() {
4. let mut s = String::from("hello, ");

6. borrow_object(s);

8. println!("Success!");
9. }

11. fn borrow_object(s: &String) {}
  1. 🌟
2. // Fix error
3. fn main() {
4. let mut s = String::from("hello, ");

6. push_str(s);

8. println!("Success!");
9. }

11. fn push_str(s: &mut String) {
12. s.push_str("world")
13. }
  1. 🌟🌟
2. fn main() {
3. let mut s = String::from("hello, ");

5. // Fill the blank to make it work
6. let p = __;

8. p.push_str("world");

10. println!("Success!");
11. }

Ref

ref can be used to take references to a value, similar to &.

  1. 🌟🌟🌟
2. fn main() {
3. let c = '中';

5. let r1 = &c;
6. // Fill the blank,dont change other code
7. let __ r2 = c;

9. assert_eq!(*r1, *r2);

11. // Check the equality of the two address strings
12. assert_eq!(get_addr(r1),get_addr(r2));

14. println!("Success!");
15. }

17. // Get memory address string
18. fn get_addr(r: &char) -> String {
19. format!("{:p}", r)
20. }

Borrowing rules

  1. 🌟
2. // Remove something to make it work
3. // Don't remove a whole line !
4. fn main() {
5. let mut s = String::from("hello");

7. let r1 = &mut s;
8. let r2 = &mut s;

10. println!("{}, {}", r1, r2);

12. println!("Success!");
13. }

Mutability

  1. 🌟 Error: Borrow an immutable object as mutable
2. fn main() {
3. // Fix error by modifying this line
4. let  s = String::from("hello, ");

6. borrow_object(&mut s);

8. println!("Success!");
9. }

11. fn borrow_object(s: &mut String) {}
  1. 🌟🌟 Ok: Borrow a mutable object as immutable
2. // This code has no errors!
3. fn main() {
4. let mut s = String::from("hello, ");

6. borrow_object(&s);

8. s.push_str("world");

10. println!("Success!");
11. }

13. fn borrow_object(s: &String) {}

NLL

  1. 🌟🌟
2. // Comment one line to make it work
3. fn main() {
4. let mut s = String::from("hello, ");

6. let r1 = &mut s;
7. r1.push_str("world");
8. let r2 = &mut s;
9. r2.push_str("!");

11. println!("{}",r1);
12. }
  1. 🌟🌟
2. fn main() {
3. let mut s = String::from("hello, ");

5. let r1 = &mut s;
6. let r2 = &mut s;

8. // Add one line below to make a compiler error: cannot borrow `s` as mutable more than once at a time
9. // You can't use r1 and r2 at the same time
10. }

You can find the solutions here(under the solutions path), but only use it when you need it