연두색연필
LimePencil's Log
연두색연필
전체 방문자
오늘
어제

About Me

  • GitHub
  • Instagram
  • Gmail

인기 글

  • 분류 전체보기 (70)
    • Machine Learning (3)
      • MNIST (2)
    • PS & Algorithm (9)
    • Web (4)
      • HTML (1)
      • JavaScript (3)
    • Rust (2)
      • The Rust Programming Langua.. (2)
    • 논문 리뷰 (12)
      • Reinforcement Learning (10)
      • Computer Vision (2)
    • DevOps (17)
      • Docker (9)
      • Kubernetes (8)
    • Development (6)
      • SQL (6)
    • 잡다한 것들 (15)
      • 부스트캠프 AI Tech 4기 (13)

최근 댓글

Tag

  • ML
  • 부스트캠프
  • docker
  • Python
  • 파이썬
  • 백준
  • 쿠버네티스
  • 도커
  • K8s
  • Kubernetes
07-15 00:08
hELLO · Designed By 정상우.
연두색연필

LimePencil's Log

Rust/The Rust Programming Language

[The Rust Programming Language] Ch. 2: Programming a Guessing Game

2023. 11. 5. 20:14

https://rust-book.cs.brown.edu/ch02-00-guessing-game-tutorial.html

 

Programming a Guessing Game - The Rust Programming Language

Let’s jump into Rust by working through a hands-on project together! This chapter introduces you to a few common Rust concepts by showing you how to use them in a real program. You’ll learn about let, match, methods, associated functions, external crat

rust-book.cs.brown.edu

Setting Up a New Project

$ cargo new guessing_game
$ cd guessing_game

cargo new creates a new cargo project with a name as the argument.

Processing a Guess

use std::io; can be used to process the input.

println! is a macro for printing string to a screen

Storing Values with Variables

let can be used to create a variable.

mut makes the variable to be mutable. Every object in Rust is mutable by default

Associated function is a function that’s implemented on a type. :: is used to describe the associated function.

  • ex) String::new()

Receiving User Input

io::stdin().read_line(&mut guess) can be used to harness user input.

  • guess is where the value read will be stored and it is referenced by &. &mut references and mutates the data.

Handling Potential Failure with Result

Result is used to handle error

  • Ok indicates the operation was successful, and it contains the generated value
  • Err means that the operation failed, and it contains information about how or why the operation failed.
  • using expect method allows for the handling of Err without needing for program to crash

Printing Values with println! Placeholders

{} can hold value in place.

  • a variable can go into the place
  • println!("You guessed: {guess}");
  • if the brackets are left blank, a comma-separated list can be followed to go in place of curly brackets
  • let x = 5; let y = 10; println!("x = {x} and y + 2 = {}", y + 2);

Testing the First Part

cargo run can be used to run the rust file.

Using a Crate to Get More Functionality

Since Rust does not provide a standard library for randomness, rand crate must be used.

library crate: code that is intended to be used in other programs and can’t be executed on its own

binary crate: code that is executable

[dependencies]
rand = "0.8.5"

Adding line above in Cargo.toml file can add dependencies to the programs.

Running cargo build after adding rand crate to the file downloads and compiles the dependencies.

  • Running the code once again does nothing because Rust knows that nothing has been changed

**Cargo.lock** file records all the dependencies’ versions used in the program, and this is for reproducibility.

Generating a Random Number

let secret_number = rand::thread_rng().gen_range(1..=100);

gen_range function takes in range as input and returns a random number in that range.

  • 1..=100 is used to represent a range of numbers between 1 and 100, inclusive

Comparing the Guess to the Secret Number

by using std::cmp::Ordering type, can be used to get variants Less, Greater, Equal.

match guess.cmp(&secret_number) {
    Ordering::Less => println!("Too small!"),
    Ordering::Greater => println!("Too big!"),
    Ordering::Equal => println!("You win!"),
}

cmp compares a variable to another variable.

match expression decides what operation to execute based on the patterns of the return value

parse method converts numbers automatically based on Rust’s default inference of value.

  • only work on characters that can logically be converted into numbers and so can easily cause errors

Allowing Multiple Guesses with Looping

loop keyword creates an infinite loop. It works the same as while True in Python.

break keyword exits the loop when the statement is executed.

 

 

 

 

'Rust > The Rust Programming Language' 카테고리의 다른 글

[The Rust Programming Language] Ch. 3: Common Programming Concepts Variables and Mutability  (0) 2023.11.05
    'Rust/The Rust Programming Language' 카테고리의 다른 글
    • [The Rust Programming Language] Ch. 3: Common Programming Concepts Variables and Mutability
    연두색연필
    연두색연필
    ML, Programming, PS, 삶의 순간을 기록

    티스토리툴바