Quiz
General Q&A on Rust.
Option
Q: Can you implement a trait on a type you did not define
A: Yes! But you cannot implement an external trait (one that you did not define) on an external type (one that you did not define).Q: Including code
A:Here is a anchor1:
struct Paddle {
hello: f32,
}
Here is a anchor2:
impl System for MySystem {
fn foo() {
println!("bar");
}
}
This is the anchor3.
/* I think I was playing around with a vscode anchor extension */
struct Paddle {
hello: f32,
}
impl System for MySystem {
fn foo() {
println!("bar");
}
}
Q: How to read a line from stdin?
A:// this does not work in playground since the stdin fails use std::io; use std::io::Write; fn main() { let mut s = String::new(); print!("Please enter something: "); io::stdin().read_line(&mut s).expect("Failed to read line from stdin"); println!("\nYou entered: <<{}>>", s); }
Q: What happens here upon unwrap?
let x:Option<u32> = None.unwrap();
A: The program panics! You cannot unwrap() a None, use `unwrap_or(...)` insteadlet x:Option<u32> = None.unwrap();
Q: What is the difference between unwrap_or and `unwrap_or_else`?
A: `unwrap_or_else` is lazy, `unwrap_or` is eager.
So unwrap_or_else is generally for passing a closure which is evaluated only when needed and unwrap_or is for an existing literal value known at the time of execution. `unwrap_or_else` expects a `Fn<()>` so you cannot just provide a literal or a simple expression.
`unwrap_or` on the otherhand will not accept a closure.
fn foo(k: u32) -> u32 { println!("eager ran"); 2 * k } assert_eq!(Some("car").unwrap_or("bike"), "car"); assert_eq!(None.unwrap_or("bike"), "bike"); assert_eq!(None.unwrap_or_else(||{ "bike" }), "bike"); let k = 10; assert_eq!(Some(4).unwrap_or(foo(k)), 4); assert_eq!(Some(4).unwrap_or_else(|| {println!("lazy did not run"); 2 * k}), 4); assert_eq!(None.unwrap_or_else(|| {println!("lazy ran"); 2 * k}), 20); println!("it ran");