๊ด€๋ฆฌ ๋ฉ”๋‰ด

IT’s Portfolio

[Rust] Start Rust (Day 2) - Guessing Game [1] ๋ณธ๋ฌธ

Development Study/Rust

[Rust] Start Rust (Day 2) - Guessing Game [1]

f1r3_r41n 2022. 8. 9. 13:29
728x90
๋ฐ˜์‘ํ˜•

๐Ÿฆ€ Rust Day 2

์ˆซ์ž ๋งž์ถ”๊ธฐ ๊ฒŒ์ž„ ๊ตฌํ˜„ ํŒŒํŠธ์˜ ๋ณ€์ˆ˜์™€ ์ž…์ถœ๋ ฅ

Code

use std::io;

fn main() {
    println!("๋žœ๋ค ์ˆซ์ž๋ฅผ ๋งžํ˜€๋ณด์„ธ์š”!");
    println!("์˜ˆ์ƒ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.");

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("์ž…๋ ฅํ•œ ๊ฐ’์„ ์ฝ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.");

    println!("์ž…๋ ฅํ•œ ๊ฐ’: {}", guess);
}
  • use std::io
    • ์ž…์ถœ๋ ฅ ๊ด€๋ จ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
    • std ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ io ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๊ฒ ๋‹ค๋Š” ์˜๋ฏธ
  • let mut
    • let: ๋ณ€์ˆ˜ ์ƒ์„ฑ
    • mut: mutable, ๊ฐ’์„ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๋Š” ๋ณ€์ˆ˜์ž„์„ ์ •์˜
      • Rust์˜ ๋ณ€์ˆ˜๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ๊ฐ’์„ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์—†์Œ(immutable)
  • guess = String::new()
    • String::new()์˜ ์‹คํ–‰ ๊ฒฐ๊ณผ๋ฅผ ๋ณ€์ˆ˜ guess์˜ ๋ฐ”์ธ๋”ฉ ๊ฐ’์œผ๋กœ ์ง€์ •
    • :: => new()๊ฐ€ String ํƒ€์ž…์˜ ์—ฐ๊ด€ ํ•จ์ˆ˜(associated function)๋ผ๋Š” ๊ฒƒ์„ ์˜๋ฏธ
      • new(): ๋นˆ ๋ฌธ์ž์—ด ์ƒ์„ฑ
      • ์—ฐ๊ด€ ํ•จ์ˆ˜(associated function): ํŠน์ •ํ•œ ์ธ์Šคํ„ด์Šค๊ฐ€ ์•„๋‹ˆ๋ผ ํƒ€์ž… ์ž์ฒด์— ๊ตฌํ˜„๋œ ํ•จ์ˆ˜ == Static method
  • io::stdin().read_line()
  • &: ์ฐธ์กฐ(reference) ํƒ€์ž…
  • {}: ์ž๋ฆฌ ์ง€์ •์ž(place holder)
  • read_line(String): io::Result ํƒ€์ž…์˜ ๊ฐ’ ๋ฆฌํ„ด
    • Result - enums(Ok, Err)
      • expect(): Result ํƒ€์ž…์˜ ์—ฐ๊ด€ ํ•จ์ˆ˜
      • Result ํƒ€์ž…์˜ ์ธ์Šคํ„ด์Šค๊ฐ€ Err ๊ฐ’์ด๋ผ๋ฉด expect ๋ฉ”์„œ๋“œ๋Š” ํ”„๋กœ๊ทธ๋žจ์˜ ์‹คํ–‰์„ ์ข…๋ฃŒํ•˜๊ณ  expect ๋ฉ”์„œ๋“œ์— ์ธ์ˆ˜๋กœ ์ „๋‹ฌํ•œ ๋ฉ”์‹œ์ง€๋ฅผ ํ‘œ์‹œ. Ok๋ผ๋ฉด expect ๋ฉ”์„œ๋“œ๋Š” Ok ๊ฐ’์ด ๋ณด๊ด€ํ•˜๊ณ  ์žˆ๋Š” ๊ฐ’๋งŒ์„ ์ฝ์–ด์™€ ๋ฆฌํ„ด
        • Python์˜ ์˜ˆ์™ธ์ฒ˜๋ฆฌ try, except ๋ฌธ๊ณผ ๋น„์Šทํ•จ
728x90
๋ฐ˜์‘ํ˜•
Comments