创建项目

  1. [root@itoracle test]# cargo new guessing_game
  2. Created binary (application) `guessing_game` package
  3. [root@itoracle test]# cd guessing_game
  4. [root@itoracle guessing_game]# ls
  5. Cargo.toml src
  6. [root@itoracle guessing_game]# cat Cargo.toml
  7. [package]
  8. name = "guessing_game"
  9. version = "0.1.0"
  10. authors = ["tanpf <itoracle@163.com>"]
  11. edition = ""
  12.  
  13. [dependencies]

the main function is the entry point into the program

  1. # vim src/main.rs
  2.  
  3. use std::io;
  4.  
  5. fn main() {
  6. println!("Guess the number!");
  7. println!("Please input your guess.");
  8. let mut guess = String::new();
  9.  
  10. io::stdin().read_line(&mut guess)
  11. .expect("Failed to read line");
  12.  
  13. println!("You guessed: {}", guess);
  14. }

println! is a macro that prints a string to the screen, then create a place to store the user input

Notice that this is a 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:
  1. let foo = ; // immutable
  2. let mut bar = ; // mutable
  1. 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.
  2.  
  3. 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.
  4.  
  5. This new function creates a new, empty string. Youll find a new function on many types, because its a common name for a function that makes a new value of some kind.
  6.  
  7. 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

  1. io::stdin().read_line(&mut guess)
  2. .expect("Failed to read line");
  1. If we hadnt 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.
  2.  
  3. 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. Were also passing one argument to read_line: &mut guess.
  4.  
  5. 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 Rusts major advantages is how safe and easy it is to use references. You dont 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.
  1. .expect("Failed to read line");
  1. As mentioned earlier, read_line puts what the user types into the string were passing it, but it also returns a valuein 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.
  2.  
  3. 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 enums variants.
  4.  
  5. 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.
  6.  
  7. If you dont call expect, the program will compile, but youll get a warning.
  1. println!("You guessed: {}", guess);
  1. let x = ;
  2. let y = ;
  3.  
  4. println!("x = {} and y = {}", x, y);

This code would print x = 5 and y = 10.

代码运行如下,

  1. [root@itoracle src]# cargo run
  2. Finished dev [unoptimized + debuginfo] target(s) in .01s
  3. Running `/usr/local/automng/src/rust/test/guessing_game/target/debug/guessing_game`
  4. Guess the number!
  5. Please input your guess.
  6. happly new year
  7. You guessed: happly new year

至此,完成了界面输入、程序输出的用户交互的过程。

获取随机数使用了rand ,这须先配置外部依赖

  1. [root@itoracle guessing_game]# vim Cargo.toml
  2.  
  3. [package]
  4. name = "guessing_game"
  5. version = "0.1.0"
  6. authors = ["tanpf <itoracle@163.com>"]
  7. edition = ""
  8.  
  9. [dependencies]
  10. 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.”

  1. [root@itoracle guessing_game]# cargo build
  2. Updating crates.io index
  3. Downloaded rand v0.3.22
  4. Downloaded rand v0.4.5
  5. Downloaded libc v0.2.47
  6. Compiling libc v0.2.47
  7. Compiling rand v0.4.5
  8. Compiling rand v0.3.22
  9. Compiling guessing_game v0.1.0 (/usr/local/automng/src/rust/test/guessing_game)
  10. 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:

  1. # cargo update
  2. 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:

  1. [dependencies]
  2.  
  3. rand = "0.4.0"

获取随机数

  1. use std::io;
  2. use rand::Rng;
  3.  
  4. fn main() {
  5. println!("Guess the number!");
  6.  
  7. let secret_number = rand::thread_rng().gen_range(, );
  8.  
  9. println!("The secret number is: {}", secret_number);
  10.  
  11. println!("Please input your guess.");
  12.  
  13. let mut guess = String::new();
  14.  
  15. io::stdin().read_line(&mut guess)
  16. .expect("Failed to read line");
  17.  
  18. println!("You guessed: {}", guess);
  19. }

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

  1. [root@itoracle guessing_game]# cargo run
  2. Compiling guessing_game v0.1.0 (/usr/local/automng/src/rust/test/guessing_game)
  3. Finished dev [unoptimized + debuginfo] target(s) in .55s
  4. Running `target/debug/guessing_game`
  5. Guess the number!
  6. The secret number is:
  7. Please input your guess.
  8.  
  9. You guessed:
  10.  
  11. [root@itoracle guessing_game]# cargo run
  12. Finished dev [unoptimized + debuginfo] target(s) in .06s
  13. Running `target/debug/guessing_game`
  14. Guess the number!
  15. The secret number is:
  16. Please input your guess.
  17.  
  18. You guessed:
  1. [root@itoracle src]# cat main.rs
  2. use std::io;
  3. use std::cmp::Ordering;
  4. use rand::Rng;
  5.  
  6. fn main() {
  7. println!("Guess the number!");
  8.  
  9. let secret_number = rand::thread_rng().gen_range(, );
  10.  
  11. println!("The secret number is: {}", secret_number);
  12.  
  13. println!("Please input your guess.");
  14.  
  15. let mut guess = String::new();
  16.  
  17. io::stdin().read_line(&mut guess)
  18. .expect("Failed to read line");
  19.  
  20. let guess: u32 = guess.trim().parse()
  21. .ok()
  22. .expect("Please type a number!");
  23.  
  24. println!("You guessed: {}", guess);
  25.  
  26. match guess.cmp(&secret_number) {
  27. Ordering::Less => println!("Too small!"),
  28. Ordering::Greater => println!("Too big!"),
  29. Ordering::Equal => println!("You win!"),
  30. };
  31. }

cpm方法要求对比的数据类型一致,所以对比前先将字符串类型的guess转换成u32(无符号32位整形),trim可以去掉字符串前后的空字符。ok与expect则是进行异常处理。

运行

  1. [root@itoracle src]# cargo run
  2. Finished dev [unoptimized + debuginfo] target(s) in .02s
  3. Running `/usr/local/automng/src/rust/test/guessing_game/target/debug/guessing_game`
  4. Guess the number!
  5. The secret number is:
  6. Please input your guess.
  7.  
  8. You guessed:
  9. You win!

1.3 guessing game的更多相关文章

  1. 2632: [neerc2011]Gcd guessing game

    2632: [neerc2011]Gcd guessing game Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 144  Solved: 84[S ...

  2. HDU 5955 Guessing the Dice Roll

    HDU 5955 Guessing the Dice Roll 2016 ACM/ICPC 亚洲区沈阳站 题意 有\(N\le 10\)个人,每个猜一个长度为\(L \le 10\)的由\(1-6\) ...

  3. Codeforces Gym 100015G Guessing Game 差分约束

    Guessing Game 题目连接: http://codeforces.com/gym/100015/attachments Description Jaehyun has two lists o ...

  4. [USACO 08JAN]Haybale Guessing

    Description The cows, who always have an inferiority complex about their intelligence, have a new gu ...

  5. [USACO08JAN]haybale猜测Haybale Guessing

    题目描述 The cows, who always have an inferiority complex about their intelligence, have a new guessing ...

  6. Gym 100096D Guessing game

    Gym 100096D Guessing game 题面 Problem Description Byteman is playing a following game with Bitman. Bi ...

  7. hdu5955 Guessing the Dice Roll【AC自动机】【高斯消元】【概率】

    含高斯消元模板 2016沈阳区域赛http://acm.hdu.edu.cn/showproblem.php?pid=5955 Guessing the Dice Roll Time Limit: 2 ...

  8. hdu 5955 Guessing the Dice Roll 【AC自动机+高斯消元】

    hdu 5955 Guessing the Dice Roll [AC自动机+高斯消元] 题意:给出 n≤10 个长为 L≤10 的串,每次丢一个骰子,先出现的串赢,问获胜概率. 题解:裸的AC自动机 ...

  9. 洛谷 P2898 [USACO08JAN]haybale猜测Haybale Guessing 解题报告

    [USACO08JAN]haybale猜测Haybale Guessing 题目描述 给一段长度为\(n\),每个位置上的数都不同的序列\(a[1\dots n]\)和\(q\)和问答,每个问答是\( ...

  10. POJ 3657 Haybale Guessing(区间染色 并查集)

    Haybale Guessing Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 2384   Accepted: 645 D ...

随机推荐

  1. C++中的友元

    友元函数 在类的声明中可以声明某一个函数作为该类的友元函数,然后该函数就可以访问类中的private数据成员了. demo: /* wirten by qianshou 2013/12/6 04:13 ...

  2. 分布式锁1 Java常用技术方案【转载】

    前言:       由于在平时的工作中,线上服务器是分布式多台部署的,经常会面临解决分布式场景下数据一致性的问题,那么就要利用分布式锁来解决这些问题.所以自己结合实际工作中的一些经验和网上看到的一些资 ...

  3. revit导出模型数据到sqlserver数据库

    revit软件可以导出模型数据到sqlserver数据库,有时候,为了对模型做数据分析,需要导出模型的数据,下面总结一下导出过程: 首先在sqlserver中建立一个数据库,如:revit_wujin ...

  4. nginx关闭php报错页面显示

    默认情况下nginx是会显示php的报错的,如果要关闭报错显示,需要在/usr/local/php7/etc/php-fpm.d/www.conf文件里面设置,貌似默认情况下在php.ini关闭没效果 ...

  5. 3、PACBIO下机数据如何看

    转载:http://www.cnblogs.com/jinhh/p/8328818.html 三代测序的下机数据都有哪些,以及他们具体的格式是怎么样的(以sequel 平台为主). 测序过程 SMRT ...

  6. Excel课程学习第三课排序与替换

    一.排序 1.简单排序 点到某一个单元格,然后选择排序,就可以按照相应的顺序来排序. 2.自定义排序 按照重要性条件来排序 也可以按照重要性从轻到重挨个排序. 3.按颜色排序 4. 按照中文数字排序, ...

  7. 解决:kali linux 在vmware 虚拟机中使用bridge模式上网的问题

    安装kali后,使用独立ip上网,但是设置bridge模式后依然上不了网,后来查了好多资料才解决。 能ping通网页,能ping通DNS,就是不能打开网页。 最后的原因是主机的防火墙拦截,把防火墙关了 ...

  8. webservice服务及客户端 编程 - 入门

    开发工具 eclipse 建立一个简单的webservice服务 1 创建服务 (1)创建一个 java项目(java project)或 web项目(Dynamic web project) (2) ...

  9. Android下创建一个输入法

    输入法是一种可以让用户输入文字的控件.Android提供了一套可扩展的输入法框架,使得应用程序可以让用户选择各种类型的输入法,比如基于触屏的键盘输入或者基于语音.当安装了特定输入法之后,用户即可在系统 ...

  10. 如何在页面中使用svg图标

    1.svg图标长啥样 注意:图标的宽高无所谓,使用时可以根据需求修改,fill后面是颜色的填充,可修改图标颜色. <svg viewBox="0 0 1024 1024" v ...