-1- 러스트를 배우자 (1Learn_Rust)
1. 소유권과 빌림(Ownership and Borrowing)
- 소유권(Ownership)
Rust의 모든 변수(value)는 단일 소유자가 있다.
소유자가 범위를 벗어나면 Rust는 자동으로 연관된 메모리를 할당 해제한다.
- 빌림(Borrowing)
소유권을 이전하는 대신, Rust는 값에 대한 참조를 허용.
&T
로 사용가능(읽기전용)
- 가변참조(mutable reference)
가변참조는 읽기 - 쓰기 권한을 가짐.
&mut T
로 사용가능
- 수명(Lifetimes)
수명은 compiler(borrow checker)가 모든 빌림이 유효한지 확인하는데 사용.
#include <stdio.h> #include <stdlib.h> void unsafe() { int *ptr = malloc(sizeof(int)); *ptr = 42; printf("%d\n", *ptr); free(ptr); printf("%d\n", *ptr); } int main() { unsafe(); return 0; }
42
-720431971(더미값)
이런 결함을 컴파일 단계에서 막아준다는 것이다!..
2. 기본구문
- 변수(Variables)
let x = 5; // 불변(Immutable) let mut y = 10; // 가변(Mutable)
- 제어흐름(Control Flow)
if x < y { println!("x is less than y"); } else if x > y { println!("x is greater than y"); } else { println!("x is equal to y"); }
함수(Functions)
a,b를 더한 값을 return 하는 함수 예시 :
fn add(a: i32, b: i32) -> i32 { a + b }