ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • rust 02
    2021/개발 2021. 6. 9. 20:59

    소유권(Ownership)

    
    // main.rs
    
    fn main() {
        // move
        let s1 = String::from("hello");
        let s2 = s1;
    
        println!("{}", s1);
    }

    하하하하하하하하하

    fn main() {
        // clone
        let s1 = String::from("hello");
        let s2 = s1.clone();
    
        println!("s1: {}, s2: {}", s1, s2);    // s1: hello, s2: hello
    }

    하하하하하하하하하하하하하

    fn main() {
        // copy
        let x = 5;
        let y = x;
    
        println!("x: {}, y: {}", x, y);        // x: 5, y: 5
    }

    하하하하하하하하하하하하하하하하하하하

    fn main() {
       // Onwership check
        let s = String::from("hello");            // s는 scope 안에 있음
        takes_ownership(s);                        // s의 값이 함수로 이동
                                                // 더이상 해당 스코프에서 유효하지 않음
        // println!("{}", s);                    // error!
    
        let x = 5;                                // x도 scope 안으로
        makes_copy(x);                            // i32는 Copy 되므로 계속 사용 가능
        // println!("{}", x);                    // Okay!
    }
    
    fn takes_ownership(some_string: String) {    // some_string이 scope에 들어옴
        println!("{}", some_string);
    }                                            // 여기에서 some_string이 scope 밖으로 벗어나고 `drop` 호출
                                                // 메모리 해제
    
    fn makes_copy(some_integer: i32) {            // some_integer 가 scope에 들어옴
        println!("{}", some_integer);
    }                                            // scope 밖으로 벗어나지만. 별다른 일이 발생하지 않음
    

    '2021 > 개발' 카테고리의 다른 글

    rust 04  (0) 2021.06.15
    rust 03  (0) 2021.06.11
    rust 01  (0) 2021.06.08
    0002 - Layout System  (0) 2021.01.18
    0001 - Props / State  (0) 2021.01.10
Designed by Tistory.