소유권과 빌림
Rust References and Borrowing
Let a function use a value without taking it: & to read, &mut to change.
배울 내용
- & and &mut
- Borrowing in function calls
- Many readers or one writer
Borrow → what it allows
length(&message)read onlyadd_exclamation(&mut message)can change itlet first = &messagemany readers are fineUse a value without owning it
A reference lets code use a value without owning it. This is called borrowing. &value borrows for reading and &mut value borrows for changing.
length only reads the text, so it takes &str and message can still be used afterwards. add_exclamation needs &mut String to change it. Rust allows many readers at once or one writer, but never both, which rules out data races at compile time.
핵심 포인트
- &value borrows for reading.
- &mut value borrows for changing.
- Many readers or one writer, never both.
실행 가능한 Rust 예제
Rust
main.rs
fn length(text: &str) -> usize {
text.len()
}
fn add_exclamation(text: &mut String) {
text.push('!');
}
fn main() {
let mut message = String::from("Borrow me");
let size = length(&message); // immutable borrow
println!("{message} has {size} bytes");
add_exclamation(&mut message); // mutable borrow
println!("{message}");
let first = &message;
let second = &message; // many readers are fine
println!("{first} {second}");
}
Borrow me has 9 bytes
Borrow me!
Borrow me! Borrow me!연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- 제로 이동 모든 0을 리스트의 끝으로 옮기되, 나머지 값들의 순서는 유지하세요. 쉬움
- 배열을 비감소 배열로 만들기 각 값이 바로 앞의 값보다 작지 않도록 만들기 위해 필요한 최소 증가 횟수를 구하세요. 쉬움