4-7 - Ownership, Structs, Enums, Match, Crates Flashcards

4. Understanding Ownership 5. Using Structs to Structure Related Data 6. Enums and Patterns Matching 7. Managing Growing Projects with Packages, Crates, and Modules

1
Q
What will be the error in the following code?
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
let r3 = &mut s;
println!("{}, {}, and {}", r1, r2, r3);
A

Cannot borrow ‘s’ as mutable because it is also borrowed as immutable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
  1. Define a tuple with 3 elements of different types.
  2. Print the tuple
  3. Print the middle element
A
let a = (String::new(), 4, 3.14);
println!("All tuple: {:?}", a);
println!("middle element: {}", a.1);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
Given an object of type User with the following definition:
struct User {
  username: String, 
  email: String,
  sign_in_count: u64, 
  active: bool,
}
Create user2 from user1 by updating only the username and email fields.
A

let user2 = User {
username: String::from(“otheruser177”);
email: String::from(“otheruser@example.com”);
..user1
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. Define a 3D point using a tuple struct.

2. Create a point variable.

A
struct Point(i32, i32, i32);
let origin = Point(0, 0, 0);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
Make the following test pass:
#[test]
fn it_works() {
  let rect1 = Rectangle {width: 30, height: 50 };
  println!("{:?} area is {}", rect1, rect1.area());
  assert_eq!(1500, rect1.area());
}
A
#[derive(Debug)]
struct Rectangle {
  width: u32,
  height: u32,
}
impl Rectangle {
  fn area(&self) -> u32 {
    self.width * self.height
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Describe the automatic referencing and dereferencing feature in Rust.

A

Calling methods is one of the few places in Rust that has this behavior.
when you call a method with object.something(), Rust automatically adds in &, &mut, or * so object matches the signature of the method.

In other words, given the receiver and name of a method, Rust can figure out definitively whether the method is reading (&self), mutating (&mut self), or consuming (self).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What’s the compilation error in the following function?

fn plus_one(x: Option) -> Option {
    match x {
        Some(i) => Some(i + 1),
    }
}
A

Matches must be exhaustive!

pattern ‘None’ not covered.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Write the following with a match statement:
let mut count = 0;
if let Coin::Quarter(state) = coin {
println!(“State quarter from {:?}!”, state);
} else {
count += 1;
}

A
let mut count = 0;
match coin {
  Coin::Quarter(state) => println!("State quarter from {:?}!", state),
  _ => count += 1,
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Write the following with a if let statement:
let mut count = 0;
match coin {
Coin::Quarter(state) => println!(“State quarter from {:?}!”, state),
_ => count += 1,
}

A
let mut count = 0;
    if let Coin::Quarter(state) = coin {
        println!("State quarter from {:?}!", state);
    } else {
        count += 1;
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
Define:
1. Packages
2. Crates
3. Modules
4. Paths
in the context of the module system in Rust.
A

Packages: A Cargo feature that lets you build, test, and share crates
Crates: A tree of modules that produces a library or executable
Modules and use: Let you control the organization, scope, and privacy of paths
Paths: A way of naming an item, such as a struct, function, or module

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the relation between a crate and a package in Rust?

A

A package can contain at most one library crate. It can contain as many binary crates as you’d like, but it must contain at least one crate (either library or binary).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Where is the crate root of a library crate located?

Where is the crate root of a binary crate located?

A

Cargo follows a convention that src/lib.rs is the crate root of a library crate with the same name as the package.

Cargo follows a convention that src/main.rs is the crate root of a binary crate with the same name as the package.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How can a package have multiple binary crates?

A

A package can have multiple binary crates by placing files in the src/bin directory: each file will be a separate binary crate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
What is the module tree of:
mod front_of_house {
    mod hosting {
        fn add_to_waitlist() {}
        fn seat_at_table() {}
    }
    mod serving {
        fn take_order() {}
        fn serve_order() {}
        fn take_payment() {}
    }
}
What is the absolute path of take_order and what is the relative path (from src/lib.rs)?
A
crate
 └── front_of_house
     ├── hosting
     │   ├── add_to_waitlist
     │   └── seat_at_table
     └── serving
         ├── take_order
         ├── serve_order
         └── take_payment

crate::front_of_house::hosting::take_order(); // Absolute
front_of_house::hosting::take_order(); // Relative

*module hosting is the child of module front_of_house, and front_of_house is the parent of module hosting.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
Does this compile and why? fix if necessary.
mod front_of_house {
    pub mod hosting {
        fn add_to_waitlist() {}
    }
}
pub fn eat_at_restaurant() {
    // Absolute path
    crate::front_of_house::hosting::add_to_waitlist();
}
A

Can’t call add_to_waitlist() from eat_at_restaurant() because it is private. To make it compile add “pub” to the function definition of add_to_waitlist().

Notice that front_of_house and eat_at_restaurant are “siblings” (have the same parent which is “crate”), hence they can refer each other (without using the “pub” keyword).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
What is super in Rust? explain its usage in the following code, written in src/lib.rs:
fn serve_order() {}
mod back_of_house {
    fn fix_incorrect_order() {
        super::serve_order();
    }
}
A

super keyword meaning is the parent module. In the example code given, super means “crate”, the root.

17
Q
What's wrong with the following code?
mod back_of_house {
    pub struct Breakfast {
        pub toast: String,
        seasonal_fruit: String,
    }
}

pub fn eat_at_restaurant() {
let mut meal = back_of_house::Breakfast {
toast: String::from(“Gvina”),
seasonal_fruit: String::from(“Mishmish”);
};
}

A

Can’t create an instance of Breakfast in eat_at_restaurant because the of the private field, seasonal_fruit, in eat_at_restaurant.

*On the other hand, if we make an enum public, then all of its variant are public as well

18
Q

What is the purpose of the “use” keyword

A

To bring paths into scope. For example, by adding use crate::front_of_house::hosting in the crate root, “hosting” now is a valid name in that scope.
(assuming the privacy settings are valid)

19
Q

What is the purpose of the “as” keyword

A

“as” allows you to provide a new local name in a use statement, for example:
use std::fmt::Result;
use std::io::Result as IoResult;

20
Q

What is the purpose of the combination of “pub” and “use”?

A

When we bring a name into scope with the use keyword, the name available in the new scope is private. To enable the code that calls our code to refer to that name as if it had been defined in that code’s scope, we can combine pub and use. This technique is called re-exporting because we’re bringing an item into scope but also making that item available for others to bring into their scope.

*Re-exporting is useful when the internal structure of your code is different from how programmers calling your code would think about the domain.

21
Q

Why don’t we need to add the standard library (std) to Cargo.toml?

A

Although std is also a crate that’s external to our package, it is shipped with the Rust language.

*We still need to refer to it with use to bring items from there into our package’s scope.

22
Q

Rewrite these use statements in more idiomatic way:
use std::io;
use std::io::Write;

A

use std::io::{self, Write};

23
Q

In the context of use statements, What is the name of the operator ‘*’? What does it do? What is its main idiomatic use?

A

’ is The glob operator. It is used in a “use” statement if we want to bring ALL public items defined in a path into scope. For example:
use std::collections::
;

The glob operator is often used when testing to bring everything under test into the tests module.

***The glob operator is also sometimes used as part of the prelude pattern: see the standard library documentation for more information on that pattern.

24
Q

In the following code, what does the first line do? Where front_of_house module is defined?

mod front_of_house;
pub use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
}
A

“mod front_of_house;” tells Rust to load the contents of the module from another file with the same name as the module, so front_of_house module is defined in src/front_of_house.rs.

*Additionally, we can call define the module hosting in src/frony_of_house/hosting.rs and add to src/front_of_house.rs the line:
pub mod hosting;