소유권 이해하기
{ // s 선언 전, 유효하지 않음 let s = "hello"; // s 유효 // s로 작업 } // 스코프 종료, s는 유효하지 않음
let s = String::from("hello"); let mut s = String::from("hello");
{ let s = String::from("hello"); // s 유효 // s로 작업 } // 스코프 종료, s 무효
class Wrapper { Wrapper::Wrapper() { this.a = new int; } Wrapper::~Wrapper() { delete this.a; } } { Wrapper wrapper; }
let x = 5; let y = x;
let s1 = String::from("hello"); let s2 = s1;
let s1 = String::from("hello"); let s2 = s1.clone();
fn takes_ownership(some_string: String) { // move되어 넘어온 some_string ... } // some_string는 스코프 밖으로 가서 drop 호출 fn makes_copy(some_int: i32) { // copy되어 넘어온 some_int ... } // 인자 some_int는 해제
let s = String::from("hello"); takes_ownership(s); // s는 함수로 이동되어 무효 let x = 5; makes_copy(x); // x는 함수로 복사, 여전히 유효
fn give_ownership() { let some_string = String::from("yours"); some_string // some_string 반환, 호출자 함수쪽으로 이동 } fn takes_and_gives_back(some_string: String) { // move되어 넘어온 some_string some_string // some_string 반환, 호출자 함수쪽으로 이동 }
let s1 = give_ownership(); // 반환값을 s1으로 이동 let s2 = String::from("hello"); let s3 = takes_and_gives_back(s2); // s2는 함수로 이동하여 무효, 반환 값은 s3로 이동
fn calculate_length(s: &String) -> usize { s.len() }
let s1 = String::from("hello"); let len = calculate_length(&s1);
fn change(s: &mut String) { s.push_str(" world"); }
let mut s1 = String::from("hello"); change(&mut s1); // s1 = "hello world"
let mut s1 = String::from("hello"); let r1 = &mut s1; let r2 = &mut s1; // 컴파일 에러!
let mut s1 = String::from("hello"); let r1 = &s1; let r2 = &s1; let r3 = &mut s1; // 컴파일 에러!
let mut s = String::from("hello"); let r1 = &s; let r2 = &s; println!("{r1} {r2}"); // 여기서 r1, r2 무효 let r3 = &mut s; // 참조가 없기에 r3 가변 참조 가능 println!("{r3}");
fn dangle() -> &String { let s = String::from("hello"); &s }
let d = dangle(); // 에러 발생
컬렉션(문자열, 배열 등)을 연속된 일부 요소를 참조하도록 해주는 기능
let s = String::from("hello world"); let hello = &s[0..5]; // hello let world = &s[6..11]; // world
let s = String::from("hello world"); let hello = &s[0..5]; // hello let hello2 = &s[..5]; // hello
let s = String::from("hello world"); let len = s.len(); let world = &s[6..len]; // world let world = &s[6..]; // world
fn func(s: &str) -> &str { ... }
let s = String::from("hello world"); func(&s);
let a = [1, 2, 3, 4, 5]; let slice = &a[1..3]; // [2, 3]