-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample.rs
More file actions
71 lines (59 loc) · 1.5 KB
/
example.rs
File metadata and controls
71 lines (59 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
// Trait definition
trait Drawable {
fn draw(&self);
fn get_name(&self) -> &str;
}
// Struct implementation
struct Rectangle {
name: String,
width: u32,
height: u32,
}
impl Drawable for Rectangle {
fn draw(&self) {
println!("Drawing {} ({} x {})", self.name, self.width, self.height);
}
fn get_name(&self) -> &str {
&self.name
}
}
// Generic function
fn print_info<T: Drawable>(item: &T) {
println!("Item name: {}", item.get_name());
item.draw();
}
fn main() {
// Vector with ownership example
let mut shapes: Vec<Box<dyn Drawable>> = Vec::new();
shapes.push(Box::new(Rectangle {
name: String::from("Rectangle 1"),
width: 10,
height: 20,
}));
// HashMap example
let mut map = HashMap::new();
map.insert("key1", "value1");
map.insert("key2", "value2");
// Thread-safe counter with Arc and Mutex
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..3 {
let counter_clone = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter_clone.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Final count: {}", *counter.lock().unwrap());
// Use shapes
for shape in shapes.iter() {
print_info(shape.as_ref());
}
}