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
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);
Cannot borrow ‘s’ as mutable because it is also borrowed as immutable.
- Define a tuple with 3 elements of different types.
- Print the tuple
- Print the middle element
let a = (String::new(), 4, 3.14); println!("All tuple: {:?}", a); println!("middle element: {}", a.1);
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.
let user2 = User {
username: String::from(“otheruser177”);
email: String::from(“otheruser@example.com”);
..user1
};
- Define a 3D point using a tuple struct.
2. Create a point variable.
struct Point(i32, i32, i32); let origin = Point(0, 0, 0);
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()); }
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } }
Describe the automatic referencing and dereferencing feature in Rust.
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).
What’s the compilation error in the following function?
fn plus_one(x: Option) -> Option { match x { Some(i) => Some(i + 1), } }
Matches must be exhaustive!
pattern ‘None’ not covered.
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;
}
let mut count = 0; match coin { Coin::Quarter(state) => println!("State quarter from {:?}!", state), _ => count += 1, }
Write the following with a if let statement:
let mut count = 0;
match coin {
Coin::Quarter(state) => println!(“State quarter from {:?}!”, state),
_ => count += 1,
}
let mut count = 0; if let Coin::Quarter(state) = coin { println!("State quarter from {:?}!", state); } else { count += 1; }
Define: 1. Packages 2. Crates 3. Modules 4. Paths in the context of the module system in Rust.
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
What is the relation between a crate and a package in Rust?
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).
Where is the crate root of a library crate located?
Where is the crate root of a binary crate located?
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 can a package have multiple binary crates?
A package can have multiple binary crates by placing files in the src/bin directory: each file will be a separate binary crate.
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)?
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.
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(); }
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).