본문 바로가기

Rust61

[Rust] Rc<T> 참조 카운팅 스마트 포인터 예제 (38일자) enum List { Cons(i32, Rc), Nil, } use List::{Cons, Nil}; use std::rc::Rc; fn main() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); println!("count after creating a = {}", Rc::strong_count(&a)); let b = Cons(3, Rc::clone(&a)); println!("count after creating b = {}", Rc::strong_count(&a)); { let c = Cons(4, Rc::clone(&a)); println!("count after creating c = {}", Rc::strong_count(&a)).. 2023. 1. 21.
[Rust] Ownership(소유권) 기초 예제 : &str (37일차) [예제 코드_1] fn main() { let name: &'static str = "Rust"; do_something(name); do_something(name); } fn do_something(name: &str) { println!("Hello, {:?}!", name); } [실행 결과] Hello, Rust! Hello, Rust! [예제 코드_2] fn main() { let name: &'static str = "Rust"; do_something(name.clone()); do_something(name.clone()); } fn do_something(name: &str) { println!("Hello, {:?}!", name); } [실행 결과] Hello, Rust! Hello.. 2023. 1. 20.
[Rust] Deref(역참조) 예제 (36일차) use std::ops::Deref; struct MyBox(T); impl MyBox { fn new(x: T) -> MyBox { MyBox(x) } } impl Deref for MyBox { type Target = T; fn deref(&self) -> &T { &self.0 } } fn hello(name: &str) { println!("Hello, {}!", name); } fn main() { let m = MyBox::new(String::from("Rust")); hello(&m); } https://rinthel.github.io/rust-lang-book-ko/ch15-02-deref.html 2023. 1. 19.
[Rust] Ownership(소유권) 기초 예제 : For Loop (35일차) [예제 코드_1] fn main() { let names = vec![ String::from("John"), String::from("Jane"), ]; for name in names { println!("{}", name); } } [실행 결과] John Jane [예제 코드_2] fn main() { let names = vec![ String::from("John"), String::from("Jane"), ]; for name in names { println!("{}", name); } println!("Names: {:?}", names); } [실행 결과] error[E0382]: borrow of moved value: `names` --> src/main.rs:11:29 [예제 코드_.. 2023. 1. 18.