1.3 guessing game
创建项目
[root@itoracle test]# cargo new guessing_game
Created binary (application) `guessing_game` package
[root@itoracle test]# cd guessing_game
[root@itoracle guessing_game]# ls
Cargo.toml src
[root@itoracle guessing_game]# cat Cargo.toml
[package]
name = "guessing_game"
version = "0.1.0"
authors = ["tanpf <itoracle@163.com>"]
edition = "" [dependencies]
the main
function is the entry point into the program
# vim src/main.rs use std::io; fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new(); io::stdin().read_line(&mut guess)
.expect("Failed to read line"); println!("You guessed: {}", guess);
}
println!
is a macro that prints a string to the screen, then create a place to store the user input
let
statement, which is used to create a variable. In Rust, variables are immutable by default. The following example shows how to use mut
before the variable name to make a variable mutable:let foo = ; // immutable
let mut bar = ; // mutable
You now know that let mut guess will introduce a mutable variable named guess. On the other side of the equal sign (=) is the value that guess is bound to, which is the result of calling String::new, a function that returns a new instance of a String. String is a string type provided by the standard library that is a growable, UTF- encoded bit of text. The :: syntax in the ::new line indicates that new is an associated function of the String type. An associated function is implemented on a type, in this case String, rather than on a particular instance of a String. Some languages call this a static method. This new function creates a new, empty string. You’ll find a new function on many types, because it’s a common name for a function that makes a new value of some kind. To summarize, the let mut guess = String::new(); line has created a mutable variable that is currently bound to a new, empty instance of a String
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
If we hadn’t listed the use std::io line at the beginning of the program, we could have written this function call as std::io::stdin. The stdin function returns an instance of std::io::Stdin, which is a type that represents a handle to the standard input for your terminal. The next part of the code, .read_line(&mut guess), calls the read_line method on the standard input handle to get input from the user. We’re also passing one argument to read_line: &mut guess. The & indicates that this argument is a reference, which gives you a way to let multiple parts of your code access one piece of data without needing to copy that data into memory multiple times. References are a complex feature, and one of Rust’s major advantages is how safe and easy it is to use references. You don’t need to know a lot of those details to finish this program. For now, all you need to know is that like variables, references are immutable by default. Hence, you need to write &mut guess rather than &guessto make it mutable.
.expect("Failed to read line");
As mentioned earlier, read_line puts what the user types into the string we’re passing it, but it also returns a value—in this case, an io::Result. Rust has a number of types named Result in its standard library: a generic Result as well as specific versions for submodules, such as io::Result. The Result types are enumerations, often referred to as enums. An enumeration is a type that can have a fixed set of values, and those values are called the enum’s variants. An instance of io::Result has an expectmethod that you can call. If this instance of io::Result is an Err value, expect will cause the program to crash and display the message that you passed as an argument to expect. If the read_line method returns an Err, it would likely be the result of an error coming from the underlying operating system. If this instance of io::Result is an Ok value, expect will take the return value that Ok is holding and return just that value to you so you can use it. In this case, that value is the number of bytes in what the user entered into standard input. If you don’t call expect, the program will compile, but you’ll get a warning.
println!("You guessed: {}", guess);
let x = ;
let y = ; println!("x = {} and y = {}", x, y);
This code would print x = 5 and y = 10
.
代码运行如下,
[root@itoracle src]# cargo run
Finished dev [unoptimized + debuginfo] target(s) in .01s
Running `/usr/local/automng/src/rust/test/guessing_game/target/debug/guessing_game`
Guess the number!
Please input your guess.
happly new year
You guessed: happly new year
至此,完成了界面输入、程序输出的用户交互的过程。
获取随机数使用了rand ,这须先配置外部依赖
[root@itoracle guessing_game]# vim Cargo.toml [package]
name = "guessing_game"
version = "0.1.0"
authors = ["tanpf <itoracle@163.com>"]
edition = "" [dependencies]
rand = "0.3.14"
The [dependencies]
section is where you tell Cargo which external crates your project depends on and which versions of those crates you require. In this case, we’ll specify the rand
crate with the semantic version specifier 0.3.14
.
The number 0.3.14
is actually shorthand for ^0.3.14
, which means “any version that has a public API compatible with version 0.3.14.”
[root@itoracle guessing_game]# cargo build
Updating crates.io index
Downloaded rand v0.3.22
Downloaded rand v0.4.5
Downloaded libc v0.2.47
Compiling libc v0.2.47
Compiling rand v0.4.5
Compiling rand v0.3.22
Compiling guessing_game v0.1.0 (/usr/local/automng/src/rust/test/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in .07s
Crates.io is where people in the Rust ecosystem post their open source Rust projects for others to use.
After updating the registry, Cargo checks the [dependencies]
section and downloads any crates you don’t have yet. In this case, although we only listed rand
as a dependency, Cargo also grabbed a copy of libc
, because rand
depends on libc
to work. After downloading the crates, Rust compiles them and then compiles the project with the dependencies available.
When you build a project for the first time, Cargo figures out all the versions of the dependencies that fit the criteria and then writes them to the Cargo.lock file. When you build your project in the future, Cargo will see that the Cargo.lock file exists and use the versions specified there rather than doing all the work of figuring out versions again. This lets you have a reproducible build automatically. In other words, your project will remain at 0.3.14
until you explicitly upgrade, thanks to the Cargo.lock file.
Updating a Crate to Get a New Version
When you do want to update a crate, Cargo provides another command, update
, which will ignore the Cargo.lock file and figure out all the latest versions that fit your specifications in Cargo.toml. If that works, Cargo will write those versions to the Cargo.lock file.
But by default, Cargo will only look for versions larger than 0.3.0
and smaller than 0.4.0
. If the rand
crate has released two new versions, 0.3.15
and 0.4.0
, you would see the following if you ran cargo update
:
# cargo update
Updating crates.io index
If you wanted to use rand
version 0.4.0
or any version in the 0.4.x
series, you’d have to update the Cargo.toml file to look like this instead:
[dependencies] rand = "0.4.0"
获取随机数
use std::io;
use rand::Rng; fn main() {
println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(, ); println!("The secret number is: {}", secret_number); println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess)
.expect("Failed to read line"); println!("You guessed: {}", guess);
}
The Rng
trait defines methods that random number generators implement, and this trait must be in scope for us to use those methods.
The rand::thread_rng
function will give us the particular random number generator that we’re going to use: one that is local to the current thread of execution and seeded by the operating system. Next, we call the gen_range
method on the random number generator. This method is defined by the Rng
trait that we brought into scope with the use rand::Rng
statement. The gen_range
method takes two numbers as arguments and generates a random number between them.
API文档查看
# cargo doc --open
Checking libc v0.2.47
Documenting libc v0.2.47
Checking rand v0.4.5
Documenting rand v0.4.5
Checking rand v0.3.22
Documenting rand v0.3.22
Documenting guessing_game v0.1.0 (/usr/local/automng/src/rust/test/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 12.30s
Opening /usr/local/automng/src/rust/test/guessing_game/target/doc/guessing_game/index.html
该命令生成项目引用API文档,下载/usr/local/automng/src/rust/test/guessing_game/target/doc到windows电脑,打开页面即可查看API
[root@itoracle guessing_game]# cargo run
Compiling guessing_game v0.1.0 (/usr/local/automng/src/rust/test/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in .55s
Running `target/debug/guessing_game`
Guess the number!
The secret number is:
Please input your guess. You guessed: [root@itoracle guessing_game]# cargo run
Finished dev [unoptimized + debuginfo] target(s) in .06s
Running `target/debug/guessing_game`
Guess the number!
The secret number is:
Please input your guess. You guessed:
[root@itoracle src]# cat main.rs
use std::io;
use std::cmp::Ordering;
use rand::Rng; fn main() {
println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(, ); println!("The secret number is: {}", secret_number); println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess)
.expect("Failed to read line"); let guess: u32 = guess.trim().parse()
.ok()
.expect("Please type a number!"); println!("You guessed: {}", guess); match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
};
}
cpm方法要求对比的数据类型一致,所以对比前先将字符串类型的guess转换成u32(无符号32位整形),trim可以去掉字符串前后的空字符。ok与expect则是进行异常处理。
运行
[root@itoracle src]# cargo run
Finished dev [unoptimized + debuginfo] target(s) in .02s
Running `/usr/local/automng/src/rust/test/guessing_game/target/debug/guessing_game`
Guess the number!
The secret number is:
Please input your guess. You guessed:
You win!
1.3 guessing game的更多相关文章
- 2632: [neerc2011]Gcd guessing game
2632: [neerc2011]Gcd guessing game Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 144 Solved: 84[S ...
- HDU 5955 Guessing the Dice Roll
HDU 5955 Guessing the Dice Roll 2016 ACM/ICPC 亚洲区沈阳站 题意 有\(N\le 10\)个人,每个猜一个长度为\(L \le 10\)的由\(1-6\) ...
- Codeforces Gym 100015G Guessing Game 差分约束
Guessing Game 题目连接: http://codeforces.com/gym/100015/attachments Description Jaehyun has two lists o ...
- [USACO 08JAN]Haybale Guessing
Description The cows, who always have an inferiority complex about their intelligence, have a new gu ...
- [USACO08JAN]haybale猜测Haybale Guessing
题目描述 The cows, who always have an inferiority complex about their intelligence, have a new guessing ...
- Gym 100096D Guessing game
Gym 100096D Guessing game 题面 Problem Description Byteman is playing a following game with Bitman. Bi ...
- hdu5955 Guessing the Dice Roll【AC自动机】【高斯消元】【概率】
含高斯消元模板 2016沈阳区域赛http://acm.hdu.edu.cn/showproblem.php?pid=5955 Guessing the Dice Roll Time Limit: 2 ...
- hdu 5955 Guessing the Dice Roll 【AC自动机+高斯消元】
hdu 5955 Guessing the Dice Roll [AC自动机+高斯消元] 题意:给出 n≤10 个长为 L≤10 的串,每次丢一个骰子,先出现的串赢,问获胜概率. 题解:裸的AC自动机 ...
- 洛谷 P2898 [USACO08JAN]haybale猜测Haybale Guessing 解题报告
[USACO08JAN]haybale猜测Haybale Guessing 题目描述 给一段长度为\(n\),每个位置上的数都不同的序列\(a[1\dots n]\)和\(q\)和问答,每个问答是\( ...
- POJ 3657 Haybale Guessing(区间染色 并查集)
Haybale Guessing Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 2384 Accepted: 645 D ...
随机推荐
- Blender 工具使用——模式切换
Blender 工具使用--模式切换 制作骨架时 在物件模式(Object Mode)下使用鼠标右键选中一个骨架,按Tab键,可以切换为编辑模式(Edit Mode),按Ctrl + Tab可以进入骨 ...
- p4301 [CQOI2013]新Nim游戏
传送门 分析 通过nim游戏我们可以知道我们现在的任务就是通过两轮之后使得剩余的几堆异或和为非0数 所以我们只需要在第一步使得剩余集合的任意非空子集的异或和非0即可 于是我们考虑线性基 我们知道线性基 ...
- EZOJ #88
传送门 分析 自然想到二分 我们二分一个长度,之后考虑如何线性判断是否合法 我们可以维护一个单调队列表示从i开始的长度为d的区间和的最大值 每次用一段区间和减去它包含的长度为d的区间最大值即可 但是我 ...
- Pig Latin程序设计1
Pig是一个大规模数据分析平台.Pig的基础结构层包括一个产生MapReduce程序的编译器.在编译器中,大规模并行执行依据存在.Pig的语言包括一个叫Pig Latin的文本语言,此语言有如下特性: ...
- 形式化方法的逆袭——如何找出Timsort算法和玉兔月球车中的Bug?
https://bindog.github.io/blog/2015/03/30/use-formal-method-to-find-the-bug-in-timsort-and-lunar-rove ...
- mingw和libcurl
想用curl来做rest的客户端.所以就研究下这方面东西. 1:安装mingw 为什么用mingw,小巧,必vs快,gcc了解的多一些, http://tdm-gcc.tdragon.net/down ...
- IntelliJ IDEA打可运行jar包时的错误
1.[ERROR] 'build.resources.resource.directory' 解决:需要在pom.xml的project->build->resources节点下,加入以 ...
- Google androd性能优化经典
2015年伊始,Google发布了关于Android性能优化典范的专题,一共16个短视频,每个3-5分钟,帮助开发者创建更快更优秀的Android App.课程专题不仅仅介绍了Android系统中有关 ...
- SpringMVC 配置式开发-HandlerMapping的执行流程(八)
具体看这两块是怎么执行的 下图是实现了DispatcherServlet从HandleMapping获得处理器执行链的逻辑的源代码 下面是DispatcherServlet从HandleAdaptor ...
- PHP 中for循环的一个小小改进
注意 : 1, $size这个值可以放在for循环中的第一个 ';' 前声明, 因为这个声明只会执行一次; 2, 第二个 ';' 中的内容, 会重复运行, 所以$i < $size 这个判断会每 ...