Created
May 2, 2024 06:57
-
-
Save philoniare/0ce4f4d4cc9d908fceca3c75dbc63852 to your computer and use it in GitHub Desktop.
rust questions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Basics | |
async fn main() { | |
// What is the difference between these two? | |
let s1 = "Hello World"; | |
let s2 = String::from("Hello World"); | |
// What is the difference between these two? | |
// Which is preferred in which cases? | |
fn foo(s: &str) {} | |
fn foo(s: &String) {} | |
// Is this allowed? | |
let foo: Box<str> = "Test".into(); | |
// Why do we need async/await? | |
// What is the output of the following? | |
test().await; | |
test2(); | |
} | |
async fn test() { | |
println!("Hello World"); | |
} | |
fn test2() { | |
println!("Hello World"); | |
} | |
/// Macros | |
/// What happens behind the scenes when you write #[derive(Something)] like below? | |
#[derive(PartialEq)] | |
struct Book { | |
author: String, | |
title: String, | |
contents: String, | |
} | |
/// Polymorphism | |
/// Suppose you are writing a GUI library. | |
/// - When would you use Variant 1 vs Variant 2? | |
/// - Which is more appropriate in this example? | |
struct Window { | |
// internal stuff | |
} | |
// Variant 1 | |
enum Widget { | |
Button { text: String }, | |
InputBox { text: String }, | |
} | |
fn draw(window: Window, widget: Widget) { | |
match widget { | |
Widget::Button { text } => { | |
// draw button | |
} | |
Widget::InputBox { text } => { | |
// draw inputbox | |
} | |
} | |
} | |
// Variant 2 | |
trait Drawable { | |
fn draw(self, window: Window); | |
} | |
struct Button { | |
text: String, | |
} | |
impl Drawable for Button { | |
fn draw(self, window: Window) { | |
// draw button | |
} | |
} | |
struct InputBox { | |
text: String, | |
} | |
impl Drawable for InputBox { | |
fn draw(self, window: Window) { | |
// draw inputbox | |
} | |
} | |
/// Synchronisation | |
/// There are two problems with this code: | |
/// 1. A bug. | |
/// 2. An optimization. | |
/// Try to find them. | |
pub fn main() { | |
let counter: Arc<Mutex<u32>> = Arc::new(Mutex::new(0)); | |
for i in 0..10 { | |
let counter_ = counter.clone(); | |
thread::spawn(move || { | |
let mut handle = counter_.lock().expect("Failed to lock"); | |
*handle += 1; | |
// Do some work | |
thread::sleep(Duration::from_secs(1)); | |
*handle -= 1; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment