본문 바로가기

Rust61

[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.
[Rust] Circular Reference (순환 참조) 예제 (40일차) use std::rc::Rc; use std::cell::RefCell; use List::{Cons, Nil}; #[derive(Debug)] enum List { Cons(i32, RefCell), Nil, } impl List { fn tail(&self) -> Option { match *self { Cons(_, ref item) => Some(item), Nil => None, } } } fn main() { let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); println!("a initial rc count = {}", Rc::strong_count(&a)); println!("a next item = {:?}", a.tail()); let b .. 2023. 1. 23.
[Rust] RefCell 예제 (39일차) #[derive(Debug)] enum List { Cons(Rc, Rc), Nil, } use List::{Cons, Nil}; use std::rc::Rc; use std::cell::RefCell; fn main() { let value = Rc::new(RefCell::new(5)); let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a)); *value.borrow_mut() += 10; println!("a after = {:?}", a); println!(.. 2023. 1. 22.