본문 바로가기

Study56

[Rust] Trait 예제 (44일차) #![allow(dead_code)] fn main() { trait Animal { fn eat(&self); } struct Herbivore; struct Carnivore; impl Animal for Herbivore { fn eat(&self) { println!("I eat plants"); } } impl Animal for Carnivore { fn eat(&self) { println!("I eat flesh"); } } let h = Herbivore; h.eat(); } [실행 결과] $ I eat plants fn main() { trait Animal { fn eat(&self); } struct Herbivore; struct Carnivore; impl Animal for H.. 2023. 1. 27.
[Rust] 공유 상태 동시성 예제 (Shared State Concurrency, 43일차) use std::sync::{Mutex, Arc}; use std::thread; fn main() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); } https.. 2023. 1. 26.
[Rust] Concurrency : Message Passing 예제 (42일차) use std::thread; use std::sync::mpsc; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("Hi"); tx.send(val).unwrap(); }); let received = rx.recv().unwrap(); println!("Got: {}", received); } use std::thread; use std::sync::mpsc; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("Greetings"); tx.send(val).unwrap(); p.. 2023. 1. 25.
[Rust] Concurrency : Thread 예제 (41일차) use std::thread; let handle = thread::spawn(|| { println!("Running in a new thread!"); }) use std::thread; fn main() { let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); handle.join().unwrap(); } use std::thread; struct MyStruct { data: i32, } impl MyStruct { fn new(data: i32) -> MyStruct { MyStruct { data } } fn run(&self) { println!("Running i.. 2023. 1. 24.