시작하기, 추리 게임, 보편적인 프로그래밍
rustc --version
rustup update // 업데이트 rustup self uninstall // 삭제
fn main() { println!("Hello, World!"); }
main.rs
rustc main.rs
컴파일 결과로 main.exe 생성
fn main() { }
println!("Hello, World!");
cargo new [프로젝트명]
위 명령어로 프로젝트를 생성하면 현재 폴더 하위에 [프로젝트명] 폴더 생성 후 프로젝트 생성
cargo init
현재 폴더에 프로젝트 생성
cargo build // 프로젝트 빌드 cargo run // 프로젝트 빌드 및 실행 cargo check // 프로젝트 에러 체크
간단한 문법 활용, 랜덤 생성되는 숫자를 추리하는 게임
use rand::Rng; fn main() { ... let secret_number = rand::thread_rng().gen_range(1..=100); ... }
match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } }
let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, };
loop { // (반복되는 작업들) }
fn main() { let x = 5; x = 6; // 컴파일 에러 }
러스트의 변수는 기본적으로 불변성 (immutable)
fn main() { let mut x = 5; x = 6; // 컴파일 OK }
mut 키워드를 추가하여 가변으로 만들 수 있음
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
fn main() { let x = 5; let x = x + 1; { let x = String::from("Another Type Shadowing"); } }
let guess: u32 = "42".parse().expect("Not a number!");
i8, u8, i16, u16, i32, u32 i64, u64, i128, u128, isize, usize
let x = 2.0 // f64 let y: f32 = 3.0 // f32
let sum = 5 + 10; // 덧셈 let difference = 95.5 - 4.3; // 뺄셈 let product = 4 * 30; // 곱셈 let quotient = 56.7 / 32.2; // 나눗셈 let truncated = -5 / 3; // 나눗셈2 (결과 -1) let remainder = 43 % 5; // 나머지 연산
let t = true; let f: bool = false;
let c = 'z'; let z: char = 'ℤ'; let heart_eye_cat = '';
여러 값을 하나의 타입으로 묶을 수 있는 타입 튜플(tuple)과 배열(array) 두 가지가 존재
let tup: (i32, f64, u8) = (500, 6.4, 1); let (x, y, z) = tup;
let a = [1, 2, 3, 4, 5]; let first = a[0]; let second = a[1]; let b[i32; 5] = [1, 2, 3, 4, 5]; // 명시적 배열 타입 선언 let failed = b[5]; // 런타임 에러 발생
fn main() { ... } fn another_function() { ... }
fn another_function(x: i32) { ... }
fn main() { let y = 6; }
let x = (let y = 6); // error
let y = { let x = 3; x + 1 // 이 라인의 결과가 반환됨 };
fn five() -> i32 { 5 }
// 주석입니다
if num < 5 { println!("num 은 5미만"); } else if num < 10 { println!("num 은 5 이상 10미만"); } else { println!("num 은 10 이상"); }
let condition = true; let num = if condition { 5 } else { 6 };
loop, while, for
loop { (반복될 코드) }
let mut counter = 0; let result = loop { counter += 1; if counter == 10 { break counter * 2; } };
let mut count = 0; 'counting_up: loop { println!("count = {count}"); let mut remaining = 10; loop { println!("remaining = {remaining}"); if remaining == 9 { break; } if count == 2 { break 'counting_up; } remaining -= 1; } count += 1; }
'counting_up 라벨을 바깥 루프에 적용, 안쪽 loop에서 바깥 'counting_up: loop를 break 할 수 있다!!!
while number != 0 { println!("{number}!"); number -= 1; }
let a = [10, 20, 30, 40, 50]; for element in a { println!("the value is: {element}"); }
for num in 1..4 { println!("the value is: {num}"); }
for num in (1..4).rev() { println!("the value is: {num}"); }