请选择 进入手机版 | 继续访问电脑版

4Ameta

 找回密码
 立即注册
搜索
查看: 580|回复: 0

Basic learning of【rust】programming【2】Write a guess and see game

[复制链接]

8

主题

8

帖子

49

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
49
发表于 2022-9-2 09:10:47 | 显示全部楼层 |阅读模式
Basic learning of【rust】programming【2】Write a guess and see game

Let's finish a project together to get started with rust!
This chapter will introduce some common concepts in rust and show how to use them through real programs.
You will learn let, match, method, correlation function, external crate and other knowledge!

follow-up
The details of these concepts are discussed in detail in the chapter.
In this chapter, we will do basic exercises.
We will implement a classic novice programming problem: guess the game.
It works like this: the program will randomly generate a random integer between 1 and 100.
Then it will ask the player to guess a number and enter it, and then prompt the player to guess whether it is large or small.
If you guessed right It will print a congratulatory message and exit.


  1. cargo new guessing_game
  2. $ cd guessing_game
复制代码

Cargo.toml
  1. [package]
  2. name = "guessing_game"
  3. version = "0.1.0"
  4. authors = ["Your Name <you@example.com>"]
  5. edition = "2023"
  6. [dependencies]
复制代码


src/main.rs
  1. use std::io;
  2. fn main() {
  3. println!("Guess the number!");
  4. println!("Please input your guess.");
  5. let mut guess = String::new(); //mut  is a var can change
  6. io::stdin().read_line(&mut guess)
  7. .expect("Failed to read line");
  8. println!("You guessed: {}", guess);
  9. }
复制代码
  1. $ cargo run
  2. Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
  3. Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs
  4. Running `target/debug/guessing_game`
  5. Guess the number!
  6. Please input your guess.
  7. 8
  8. You guessed: 8
复制代码



回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|4ameta

GMT+8, 2022-12-4 04:23 , Processed in 0.034596 second(s), 17 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表