코딩Coding/Rust연습

Rust연습] Cow__120 Easy Rust in Korean: to_mut with Cow

내인생PLUS 2022. 4. 19. 23:05
728x90

 

 

 

~/Documents/Project/Github/rust_project/training_rustacean_rust/src/main.rs.html
 1 use std::borrow::Cow;
 2 
 3 #[derive(Debug)]
 4 struct User<'a> {
 5     name: Cow<'a, str>,
 6 }
 7 
 8 impl User<'_> {
 9     fn is_borrowed(&self) {
10         match &self.name {
11             Cow::Borrowed(name) => println!("It's Borrowed: {name}"),
12             Cow::Owned(name) => println!("It's owned: {name}"),
13         }
14     }
15 }
16 
17 fn main() {
18     let mut user_1 = User {
19         name: "user_1".into(),
20     };
21 
22     let user_2 = User {
23         name: "User 2".to_string().into(),
24     };
25 
26     user_1.is_borrowed();
27 
28     user_1.name.to_mut().push('!');
29     user_1.is_borrowed();
30 }

 

 

 

 

 

결과

cargo run

   Compiling training_rustacean_rust v0.1.0 (/Users/globalyoung/Documents/Project/Github/rust_project/training_rustacean_rust)
warning: unused variable: `user_2`
  --> src/main.rs:22:9
   |
22 |     let user_2 = User {
   |         ^^^^^^ help: if this is intentional, prefix it with an underscore: `_user_2`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: `training_rustacean_rust` (bin "training_rustacean_rust") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.10s
     Running `target/debug/training_rustacean_rust`
It's Borrowed: user_1
It's owned: user_1!

 

 

 

4분

https://youtu.be/0m45e3UsRGs

 

반응형