rust, Ownership

lsh235·2023년 6월 9일
0

rust

목록 보기
5/7

가비지 콜렉터 없이 메모리 안정성 보장을 하게 해준다.
따라서, 소유권이 러스트 내에서 어떻게 동작하는지 이해하는 것은 중요!
관련된 특성들: 빌림, 슬라이스, 그리고 러스트가 메모리에 데이터를 저장하는지

} 괄호가 닫힐때 자동적으로 drop을 호출한다.

let s1 = String::from("hello");
let s2 = s1;

println!("{}, world!", s1);
하게 될 경우 s1은 무효화되어 다음 그림과 같음.

필요한 경우에는 clone으로 사용가능
let s1 = String::from("hello");
let s2 = s1.clone();

println!("s1 = {}, s2 = {}", s1, s2);

정수형과 같이 컴파일 타임에 결정되어 있는 크기의 타입은 스택에 모두 저장되기 때문에 깊은 복사, 얕은 복사간의 차이가 없어 다음과 같이 가능.
let x = 5;
let y = x;

println!("x = {}, y = {}", x, y);

다음과 같은 경우 s의 소유권이 사라져서 s 출력불가
let s = String::from("hello");
takes_ownership(s);
println!("{}", s);

다음과 같이 사용가능하지만 이 방법 보다는.. 참조자가 낫지 않을까 싶다.
let s1 = gives_ownership();
fn gives_ownership() -> String {
let some_string = String::from("hello");
some_string
}

참조자 사용법
fn calculate_length(s: &String) -> usize {
s.len()
}

그러나 mut없으면 변경 안되므로 변경시에는 mut
fn change(some_string: &mut String) {
some_string.push_str(", world");
}

동일한 스코프 내에서는 가변참조자는 하나만 사용
다음 코드는 불가능
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;

불변 가변 혼용 또한 불가능
let mut s = String::from("hello");
let r1 = &s; // 문제 없음
let r2 = &s; // 문제 없음
let r3 = &mut s; // 큰 문제

댕글링포인터는 해당 포인터를 사용 중인데 포인터를 해제함으로써 생기는 문제 다음 코드에서는 참조자를 반환하려 하지만 s가 스코프를 벗어나면서 해제되므로 댕글링포인터 발생. 컴파일시 불가
fn dangle() -> &String {
let s = String::from("hello");
&s
}

다음과 같이 반환 할 수 있도록
fn no_dangle() -> String {
let s = String::from("hello");
s
}

스트링 리터럴은 다음과 같이 사용가능
let s = String::from("hello");
let len = s.len();
let slice = &s[0..len];
let slice = &s[..];

따라서 다음과 같은 코드는 에러를 발생
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // Error!
println!("the first word is: {}", word);
}

0개의 댓글