-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathch02-00-guessing-game-tutorial.html
More file actions
1058 lines (937 loc) · 66 KB
/
ch02-00-guessing-game-tutorial.html
File metadata and controls
1058 lines (937 loc) · 66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Guessing Game Tutorial - Guessing Game Tutorial - The Rust Programming Language</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="">
<link rel="stylesheet" href="book.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="favicon.png">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<link rel="stylesheet" href="ayu-highlight.css">
<!-- Custom theme -->
<style>
.page-wrapper.has-warning > .nav-chapters {
/* add height for warning content & margin */
top: 120px;
}
p.warning {
background-color: rgb(242, 222, 222);
border-bottom-color: rgb(238, 211, 215);
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-bottom-style: solid;
border-bottom-width: 0.666667px;
border-image-outset: 0 0 0 0;
border-image-repeat: stretch stretch;
border-image-slice: 100% 100% 100% 100%;
border-image-source: none;
border-image-width: 1 1 1 1;
border-left-color: rgb(238, 211, 215);
border-left-style: solid;
border-left-width: 0.666667px;
border-right-color: rgb(238, 211, 215);
border-right-style: solid;
border-right-width: 0.666667px;
border-top-color: rgb(238, 211, 215);
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-top-style: solid;
border-top-width: 0.666667px;
color: rgb(185, 74, 72);
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 30px;
padding-bottom: 8px;
padding-left: 14px;
padding-right: 35px;
padding-top: 8px;
}
p.warning strong {
color: rgb(185, 74, 72)
}
p.warning a {
color: rgb(0, 136, 204)
}
a .hljs {
color: #4183c4;
}
.rust .content a .hljs,
.coal .content a .hljs,
.navy .content a .hljs {
color: #2b79a2;
}
a:hover .hljs {
text-decoration: underline;
}
/* Styles keystrokes such as ctrl-C */
.keystroke {
font-variant: small-caps;
}
</style>
<!-- Fetch Clipboard.js from CDN but have a local fallback -->
<script src="https://cdn.jsdelivr.net/clipboard.js/1.6.1/clipboard.min.js"></script>
<script>
if (typeof Clipboard == 'undefined') {
document.write(unescape("%3Cscript src='clipboard.min.js'%3E%3C/script%3E"));
}
</script>
<!-- Fetch JQuery from CDN but have a local fallback -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
}
</script>
<!-- Fetch store.js from local - TODO add CDN when 2.x.x is available on cdnjs -->
<script src="store.js"></script>
<!-- Custom JS script -->
</head>
<body class="light">
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme = store.get('mdbook-theme');
if (theme === null || theme === undefined) { theme = 'light'; }
$('body').removeClass().addClass(theme);
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var sidebar = store.get('mdbook-sidebar');
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
</script>
<div id="sidebar" class="sidebar">
<ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html" class="active"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> Common Programming Concepts</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> What is Ownership?</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Using Structs to Structure Related Data</a></li><li><ul class="section"><li><a href="ch05-01-defining-structs.html"><strong>5.1.</strong> Defining and Instantiating Structs</a></li><li><a href="ch05-02-example-structs.html"><strong>5.2.</strong> An Example Program Using Structs</a></li><li><a href="ch05-03-method-syntax.html"><strong>5.3.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums and Pattern Matching</a></li><li><ul class="section"><li><a href="ch06-01-defining-an-enum.html"><strong>6.1.</strong> Defining an Enum</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> The <code>match</code> Control Flow Operator</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> Concise Control Flow with <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Referring to Names in Different Modules</a></li></ul></li><li><a href="ch08-00-common-collections.html"><strong>8.</strong> Common Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> Generic Types, Traits, and Lifetimes</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Generic Data Types</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits: Defining Shared Behavior</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> Validating References with Lifetimes</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> Testing</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html"><strong>11.1.</strong> Writing tests</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> Running tests</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> Test Organization</a></li></ul></li><li><a href="ch12-00-an-io-project.html"><strong>12.</strong> An I/O Project: Building a Command Line Program</a></li><li><ul class="section"><li><a href="ch12-01-accepting-command-line-arguments.html"><strong>12.1.</strong> Accepting Command Line Arguments</a></li><li><a href="ch12-02-reading-a-file.html"><strong>12.2.</strong> Reading a File</a></li><li><a href="ch12-03-improving-error-handling-and-modularity.html"><strong>12.3.</strong> Refactoring to Improve Modularity and Error Handling</a></li><li><a href="ch12-04-testing-the-librarys-functionality.html"><strong>12.4.</strong> Developing the Library’s Functionality with Test Driven Development</a></li><li><a href="ch12-05-working-with-environment-variables.html"><strong>12.5.</strong> Working with Environment Variables</a></li><li><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong>12.6.</strong> Writing Error Messages to Standard Error Instead of Standard Output</a></li></ul></li><li><a href="ch13-00-functional-features.html"><strong>13.</strong> Functional Language Features: Iterators and Closures</a></li><li><ul class="section"><li><a href="ch13-01-closures.html"><strong>13.1.</strong> Closures: Anonymous Functions that Can Capture Their Environment</a></li><li><a href="ch13-02-iterators.html"><strong>13.2.</strong> Processing a Series of Items with Iterators</a></li><li><a href="ch13-03-improving-our-io-project.html"><strong>13.3.</strong> Improving Our I/O Project</a></li><li><a href="ch13-04-performance.html"><strong>13.4.</strong> Comparing Performance: Loops vs. Iterators</a></li></ul></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> More about Cargo and Crates.io</a></li><li><ul class="section"><li><a href="ch14-01-release-profiles.html"><strong>14.1.</strong> Customizing Builds with Release Profiles</a></li><li><a href="ch14-02-publishing-to-crates-io.html"><strong>14.2.</strong> Publishing a Crate to Crates.io</a></li><li><a href="ch14-03-cargo-workspaces.html"><strong>14.3.</strong> Cargo Workspaces</a></li><li><a href="ch14-04-installing-binaries.html"><strong>14.4.</strong> Installing Binaries from Crates.io with <code>cargo install</code></a></li><li><a href="ch14-05-extending-cargo.html"><strong>14.5.</strong> Extending Cargo with Custom Commands</a></li></ul></li><li><a href="ch15-00-smart-pointers.html"><strong>15.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="ch15-01-box.html"><strong>15.1.</strong> <code>Box<T></code> Points to Data on the Heap and Has a Known Size</a></li><li><a href="ch15-02-deref.html"><strong>15.2.</strong> The <code>Deref</code> Trait Allows Access to the Data Through a Reference</a></li><li><a href="ch15-03-drop.html"><strong>15.3.</strong> The <code>Drop</code> Trait Runs Code on Cleanup</a></li><li><a href="ch15-04-rc.html"><strong>15.4.</strong> <code>Rc<T></code>, the Reference Counted Smart Pointer</a></li><li><a href="ch15-05-interior-mutability.html"><strong>15.5.</strong> <code>RefCell<T></code> and the Interior Mutability Pattern</a></li><li><a href="ch15-06-reference-cycles.html"><strong>15.6.</strong> Creating Reference Cycles and Leaking Memory is Safe</a></li></ul></li><li><a href="ch16-00-concurrency.html"><strong>16.</strong> Fearless Concurrency</a></li><li><ul class="section"><li><a href="ch16-01-threads.html"><strong>16.1.</strong> Threads</a></li><li><a href="ch16-02-message-passing.html"><strong>16.2.</strong> Message Passing</a></li><li><a href="ch16-03-shared-state.html"><strong>16.3.</strong> Shared State</a></li><li><a href="ch16-04-extensible-concurrency-sync-and-send.html"><strong>16.4.</strong> Extensible Concurrency: <code>Sync</code> and <code>Send</code></a></li></ul></li><li><a href="ch17-00-oop.html"><strong>17.</strong> Is Rust an Object-Oriented Programming Language?</a></li><li><ul class="section"><li><a href="ch17-01-what-is-oo.html"><strong>17.1.</strong> What Does Object-Oriented Mean?</a></li><li><a href="ch17-02-trait-objects.html"><strong>17.2.</strong> Trait Objects for Using Values of Different Types</a></li><li><a href="ch17-03-oo-design-patterns.html"><strong>17.3.</strong> Object-Oriented Design Pattern Implementations</a></li></ul></li><li><a href="ch18-00-patterns.html"><strong>18.</strong> Patterns Match the Structure of Values</a></li><li><ul class="section"><li><a href="ch18-01-all-the-places-for-patterns.html"><strong>18.1.</strong> All the Places Patterns May be Used</a></li><li><a href="ch18-02-refutability.html"><strong>18.2.</strong> Refutability: Whether a Pattern Might Fail to Match</a></li><li><a href="ch18-03-pattern-syntax.html"><strong>18.3.</strong> All the Pattern Syntax</a></li></ul></li><li><a href="ch19-00-advanced-features.html"><strong>19.</strong> Advanced Features</a></li><li><ul class="section"><li><a href="ch19-01-unsafe-rust.html"><strong>19.1.</strong> Unsafe Rust</a></li><li><a href="ch19-02-advanced-lifetimes.html"><strong>19.2.</strong> Advanced Lifetimes</a></li><li><a href="ch19-03-advanced-traits.html"><strong>19.3.</strong> Advanced Traits</a></li><li><a href="ch19-04-advanced-types.html"><strong>19.4.</strong> Advanced Types</a></li><li><a href="ch19-05-advanced-functions-and-closures.html"><strong>19.5.</strong> Advanced Functions & Closures</a></li></ul></li><li><a href="ch20-00-final-project-a-web-server.html"><strong>20.</strong> Final Project: Building a Multithreaded Web Server</a></li><li><ul class="section"><li><a href="ch20-01-single-threaded.html"><strong>20.1.</strong> A Single Threaded Web Server</a></li><li><a href="ch20-02-slow-requests.html"><strong>20.2.</strong> How Slow Requests Affect Throughput</a></li><li><a href="ch20-03-designing-the-interface.html"><strong>20.3.</strong> Designing the Thread Pool Interface</a></li><li><a href="ch20-04-storing-threads.html"><strong>20.4.</strong> Creating the Thread Pool and Storing Threads</a></li><li><a href="ch20-05-sending-requests-via-channels.html"><strong>20.5.</strong> Sending Requests to Threads Via Channels</a></li><li><a href="ch20-06-graceful-shutdown-and-cleanup.html"><strong>20.6.</strong> Graceful Shutdown and Cleanup</a></li></ul></li><li><a href="appendix-00.html"><strong>21.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>21.1.</strong> A - Keywords</a></li><li><a href="appendix-02-operators.html"><strong>21.2.</strong> B - Operators and Symbols</a></li><li><a href="appendix-03-derivable-traits.html"><strong>21.3.</strong> C - Derivable Traits</a></li><li><a href="appendix-04-macros.html"><strong>21.4.</strong> D - Macros</a></li><li><a href="appendix-05-translation.html"><strong>21.5.</strong> E - Translations</a></li><li><a href="appendix-06-newest-features.html"><strong>21.6.</strong> F - Newest Features</a></li></ul></li></ul>
</div>
<div id="page-wrapper" class="page-wrapper has-warning">
<div class="page" tabindex="-1">
<header><p class="warning">You are reading a <strong>draft</strong> of the next edition of TRPL. For more, go <a href="../index.html">here</a>.</p></header>
<div id="menu-bar" class="menu-bar">
<div class="left-buttons">
<i id="sidebar-toggle" class="fa fa-bars"></i>
<i id="theme-toggle" class="fa fa-paint-brush"></i>
</div>
<h1 class="menu-title">The Rust Programming Language</h1>
<div class="right-buttons">
<a href="print.html">
<i id="print-button" class="fa fa-print" title="Print this book"></i>
</a>
</div>
</div>
<div id="content" class="content">
<a class="header" href="ch02-00-guessing-game-tutorial.html#guessing-game" id="guessing-game"><h1>Guessing Game</h1></a>
<p>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 <code>let</code>, <code>match</code>, methods, associated
functions, using external crates, and more! The following chapters will explore
these ideas in more detail. In this chapter, you’ll practice the fundamentals.</p>
<p>We’ll implement a classic beginner programming problem: a guessing game. Here’s
how it works: the program will generate a random integer between 1 and 100. It
will then prompt the player to enter a guess. After entering a guess, it will
indicate whether the guess is too low or too high. If the guess is correct, the
game will print congratulations and exit.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#setting-up-a-new-project" id="setting-up-a-new-project"><h2>Setting Up a New Project</h2></a>
<p>To set up a new project, go to the <em>projects</em> directory that you created in
Chapter 1, and make a new project using Cargo, like so:</p>
<pre><code class="language-text">$ cargo new guessing_game --bin
$ cd guessing_game
</code></pre>
<p>The first command, <code>cargo new</code>, takes the name of the project (<code>guessing_game</code>)
as the first argument. The <code>--bin</code> flag tells Cargo to make a binary project,
similar to the one in Chapter 1. The second command changes to the new
project’s directory.</p>
<p>Look at the generated <em>Cargo.toml</em> file:</p>
<p><span class="filename">Filename: Cargo.toml</span></p>
<pre><code class="language-toml">[package]
name = "guessing_game"
version = "0.1.0"
authors = ["Your Name <you@example.com>"]
[dependencies]
</code></pre>
<p>If the author information that Cargo obtained from your environment is not
correct, fix that in the file and save it again.</p>
<p>As you saw in Chapter 1, <code>cargo new</code> generates a “Hello, world!” program for
you. Check out the <em>src/main.rs</em> file:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust">fn main() {
println!("Hello, world!");
}
</code></pre></pre>
<p>Now let’s compile this “Hello, world!” program and run it in the same step
using the <code>cargo run</code> command:</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 1.50 secs
Running `target/debug/guessing_game`
Hello, world!
</code></pre>
<p>The <code>run</code> command comes in handy when you need to rapidly iterate on a project,
and this game is such a project: we want to quickly test each iteration
before moving on to the next one.</p>
<p>Reopen the <em>src/main.rs</em> file. You’ll be writing all the code in this file.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#processing-a-guess" id="processing-a-guess"><h2>Processing a Guess</h2></a>
<p>The first part of the program will ask for user input, process that input, and
check that the input is in the expected form. To start, we’ll allow the player
to input a guess. Enter the code in Listing 2-1 into <em>src/main.rs</em>.</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">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);
}
</code></pre>
<p><span class="caption">Listing 2-1: Code to get a guess from the user and print
it out</span></p>
<p>This code contains a lot of information, so let’s go over it bit by bit. To
obtain user input and then print the result as output, we need to bring the
<code>io</code> (input/output) library into scope. The <code>io</code> library comes from the
standard library (which is known as <code>std</code>):</p>
<pre><code class="language-rust ignore">use std::io;
</code></pre>
<p>By default, Rust brings only a few types into the scope of every program in
<a href="../../std/prelude/index.html">the <em>prelude</em></a><!-- ignore -->. If a type you want to use isn’t in the
prelude, you have to bring that type into scope explicitly with a <code>use</code>
statement. Using the <code>std::io</code> library provides you with a number of useful
<code>io</code>-related features, including the functionality to accept user input.</p>
<p>As you saw in Chapter 1, the <code>main</code> function is the entry point into the
program:</p>
<pre><code class="language-rust ignore">fn main() {
</code></pre>
<p>The <code>fn</code> syntax declares a new function, the <code>()</code> indicate there are no
parameters, and <code>{</code> starts the body of the function.</p>
<p>As you also learned in Chapter 1, <code>println!</code> is a macro that prints a string to
the screen:</p>
<pre><code class="language-rust ignore">println!("Guess the number!");
println!("Please input your guess.");
</code></pre>
<p>This code is printing a prompt stating what the game is and requesting input
from the user.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#storing-values-with-variables" id="storing-values-with-variables"><h3>Storing Values with Variables</h3></a>
<p>Next, we’ll create a place to store the user input, like this:</p>
<pre><code class="language-rust ignore">let mut guess = String::new();
</code></pre>
<p>Now the program is getting interesting! There’s a lot going on in this little
line. Notice that this is a <code>let</code> statement, which is used to create
<em>variables</em>. Here’s another example:</p>
<pre><code class="language-rust ignore">let foo = bar;
</code></pre>
<p>This line will create a new variable named <code>foo</code> and bind it to the value
<code>bar</code>. In Rust, variables are immutable by default. The following example shows
how to use <code>mut</code> before the variable name to make a variable mutable:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let foo = 5; // immutable
let mut bar = 5; // mutable
#}</code></pre></pre>
<blockquote>
<p>Note: The <code>//</code> syntax starts a comment that continues until the end of the
line. Rust ignores everything in comments.</p>
</blockquote>
<p>Now you know that <code>let mut guess</code> will introduce a mutable variable named
<code>guess</code>. On the other side of the equal sign (<code>=</code>) is the value that <code>guess</code> is
bound to, which is the result of calling <code>String::new</code>, a function that returns
a new instance of a <code>String</code>. <a href="../../std/string/struct.String.html"><code>String</code></a><!-- ignore --> is a string
type provided by the standard library that is a growable, UTF-8 encoded bit of
text.</p>
<p>The <code>::</code> syntax in the <code>::new</code> line indicates that <code>new</code> is an <em>associated
function</em> of the <code>String</code> type. An associated function is implemented on a type,
in this case <code>String</code>, rather than on a particular instance of a <code>String</code>. Some
languages call this a <em>static method</em>.</p>
<p>This <code>new</code> function creates a new, empty <code>String</code>. You’ll find a <code>new</code> function
on many types, because it’s a common name for a function that makes a new value
of some kind.</p>
<p>To summarize, the <code>let mut guess = String::new();</code> line has created a mutable
variable that is currently bound to a new, empty instance of a <code>String</code>. Whew!</p>
<p>Recall that we included the input/output functionality from the standard
library with <code>use std::io;</code> on the first line of the program. Now we’ll call an
associated function, <code>stdin</code>, on <code>io</code>:</p>
<pre><code class="language-rust ignore">io::stdin().read_line(&mut guess)
.expect("Failed to read line");
</code></pre>
<p>If we didn’t have the <code>use std::io</code> line at the beginning of the program, we
could have written this function call as <code>std::io::stdin</code>. The <code>stdin</code> function
returns an instance of <a href="../../std/io/struct.Stdin.html"><code>std::io::Stdin</code></a><!-- ignore -->, which is a
type that represents a handle to the standard input for your terminal.</p>
<p>The next part of the code, <code>.read_line(&mut guess)</code>, calls the
<a href="../../std/io/struct.Stdin.html#method.read_line"><code>read_line</code></a><!-- ignore --> method on the standard input handle to
get input from the user. We’re also passing one argument to <code>read_line</code>: <code>&mut guess</code>.</p>
<p>The job of <code>read_line</code> is to take whatever the user types into standard input
and place that into a string, so it takes that string as an argument. The
string argument needs to be mutable so the method can change the string’s
content by adding the user input.</p>
<p>The <code>&</code> indicates that this argument is a <em>reference</em>, 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: Chapter 4 will explain references more thoroughly. For now, all you
need to know is that like variables, references are immutable by default.
Hence, we need to write <code>&mut guess</code> rather than <code>&guess</code> to make it mutable.</p>
<p>We’re not quite done with this line of code. Although it’s a single line of
text, it’s only the first part of the single logical line of code. The second
part is this method:</p>
<pre><code class="language-rust ignore">.expect("Failed to read line");
</code></pre>
<p>When you call a method with the <code>.foo()</code> syntax, it’s often wise to introduce a
newline and other whitespace to help break up long lines. We could have
written this code as:</p>
<pre><code class="language-rust ignore">io::stdin().read_line(&mut guess).expect("Failed to read line");
</code></pre>
<p>However, one long line is difficult to read, so it’s best to divide it, two
lines for two method calls. Now let’s discuss what this line does.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#handling-potential-failure-with-the-result-type" id="handling-potential-failure-with-the-result-type"><h3>Handling Potential Failure with the <code>Result</code> Type</h3></a>
<p>As mentioned earlier, <code>read_line</code> puts what the user types into the string we’re
passing it, but it also returns a value—in this case, an
<a href="../../std/io/type.Result.html"><code>io::Result</code></a><!-- ignore -->. Rust has a number of types named
<code>Result</code> in its standard library: a generic <a href="../../std/result/enum.Result.html"><code>Result</code></a><!-- ignore --> as
well as specific versions for submodules, such as <code>io::Result</code>.</p>
<p>The <code>Result</code> types are <a href="ch06-00-enums.html"><em>enumerations</em></a><!-- ignore -->, often referred
to as <em>enums</em>. An enumeration is a type that can have a fixed set of values,
and those values are called the enum’s <em>variants</em>. Chapter 6 will cover enums
in more detail.</p>
<p>For <code>Result</code>, the variants are <code>Ok</code> or <code>Err</code>. <code>Ok</code> indicates the operation was
successful, and inside the <code>Ok</code> variant is the successfully generated value.
<code>Err</code> means the operation failed, and <code>Err</code> contains information about how or
why the operation failed.</p>
<p>The purpose of these <code>Result</code> types is to encode error handling information.
Values of the <code>Result</code> type, like any type, have methods defined on them. An
instance of <code>io::Result</code> has an <a href="../../std/result/enum.Result.html#method.expect"><code>expect</code> method</a><!-- ignore --> that
you can call. If this instance of <code>io::Result</code> is an <code>Err</code> value, <code>expect</code> will
cause the program to crash and display the message that you passed as an
argument to <code>expect</code>. If the <code>read_line</code> method returns an <code>Err</code>, it would
likely be the result of an error coming from the underlying operating system.
If this instance of <code>io::Result</code> is an <code>Ok</code> value, <code>expect</code> will take the
return value that <code>Ok</code> is holding and return just that value to you so you
could use it. In this case, that value is the number of bytes in what the user
entered into standard input.</p>
<p>If we don’t call <code>expect</code>, the program will compile, but we’ll get a warning:</p>
<pre><code class="language-text">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
warning: unused `std::result::Result` which must be used
--> src/main.rs:10:5
|
10 | io::stdin().read_line(&mut guess);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(unused_must_use)] on by default
</code></pre>
<p>Rust warns that we haven’t used the <code>Result</code> value returned from <code>read_line</code>,
indicating that the program hasn’t handled a possible error. The right way to
suppress the warning is to actually write error handling, but since we want to
crash this program when a problem occurs, we can use <code>expect</code>. You’ll learn
about recovering from errors in Chapter 9.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#printing-values-with-println-placeholders" id="printing-values-with-println-placeholders"><h3>Printing Values with <code>println!</code> Placeholders</h3></a>
<p>Aside from the closing curly brackets, there’s only one more line to discuss in
the code added so far, which is the following:</p>
<pre><code class="language-rust ignore">println!("You guessed: {}", guess);
</code></pre>
<p>This line prints out the string we saved the user’s input in. The set of <code>{}</code>
is a placeholder that holds a value in place. You can print more than one value
using <code>{}</code>: the first set of <code>{}</code> holds the first value listed after the format
string, the second set holds the second value, and so on. Printing out multiple
values in one call to <code>println!</code> would look like this:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x = 5;
let y = 10;
println!("x = {} and y = {}", x, y);
#}</code></pre></pre>
<p>This code would print out <code>x = 5 and y = 10</code>.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#testing-the-first-part" id="testing-the-first-part"><h3>Testing the First Part</h3></a>
<p>Let’s test the first part of the guessing game. You can run it using
<code>cargo run</code>:</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs
Running `target/debug/guessing_game`
Guess the number!
Please input your guess.
6
You guessed: 6
</code></pre>
<p>At this point, the first part of the game is done: we’re getting input from the
keyboard and then printing it.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#generating-a-secret-number" id="generating-a-secret-number"><h2>Generating a Secret Number</h2></a>
<p>Next, we need to generate a secret number that the user will try to guess. The
secret number should be different every time so the game is fun to play more
than once. Let’s use a random number between 1 and 100 so the game isn’t too
difficult. Rust doesn’t yet include random number functionality in its standard
library. However, the Rust team does provide a <a href="https://crates.io/crates/rand"><code>rand</code> crate</a>.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#using-a-crate-to-get-more-functionality" id="using-a-crate-to-get-more-functionality"><h3>Using a Crate to Get More Functionality</h3></a>
<p>Remember that a <em>crate</em> is a package of Rust code. The project we’ve been
building is a <em>binary crate</em>, which is an executable. The <code>rand</code> crate is a
<em>library crate</em>, which contains code intended to be used in other programs.</p>
<p>Cargo’s use of external crates is where it really shines. Before we can write
code that uses <code>rand</code>, we need to modify the <em>Cargo.toml</em> file to include the
<code>rand</code> crate as a dependency. Open that file now and add the following line to
the bottom beneath the <code>[dependencies]</code> section header that Cargo created for
you:</p>
<p><span class="filename">Filename: Cargo.toml</span></p>
<pre><code class="language-toml">[dependencies]
rand = "0.3.14"
</code></pre>
<p>In the <em>Cargo.toml</em> file, everything that follows a header is part of a section
that continues until another section starts. The <code>[dependencies]</code> 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 <code>rand</code>
crate with the semantic version specifier <code>0.3.14</code>. Cargo understands <a href="http://semver.org">Semantic
Versioning</a><!-- ignore --> (sometimes called <em>SemVer</em>), which is a
standard for writing version numbers. The number <code>0.3.14</code> is actually shorthand
for <code>^0.3.14</code>, which means “any version that has a public API compatible with
version 0.3.14.”</p>
<p>Now, without changing any of the code, let’s build the project, as shown in
Listing 2-2:</p>
<pre><code class="language-text">$ cargo build
Updating registry `https://github.com/rust-lang/crates.io-index`
Downloading rand v0.3.14
Downloading libc v0.2.14
Compiling libc v0.2.14
Compiling rand v0.3.14
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs
</code></pre>
<p><span class="caption">Listing 2-2: The output from running <code>cargo build</code> after
adding the rand crate as a dependency</span></p>
<p>You may see different version numbers (but they will all be compatible with
the code, thanks to SemVer!), and the lines may be in a different order.</p>
<p>Now that we have an external dependency, Cargo fetches the latest versions of
everything from the <em>registry</em>, which is a copy of data from
<a href="https://crates.io">Crates.io</a>. Crates.io is where people in the Rust ecosystem post
their open source Rust projects for others to use.</p>
<p>After updating the registry, Cargo checks the <code>[dependencies]</code> section and
downloads any you don’t have yet. In this case, although we only listed <code>rand</code>
as a dependency, Cargo also grabbed a copy of <code>libc</code>, because <code>rand</code> depends on
<code>libc</code> to work. After downloading them, Rust compiles them and then compiles
the project with the dependencies available.</p>
<p>If you immediately run <code>cargo build</code> again without making any changes, you won’t
get any output. Cargo knows it has already downloaded and compiled the
dependencies, and you haven’t changed anything about them in your <em>Cargo.toml</em>
file. Cargo also knows that you haven’t changed anything about your code, so it
doesn’t recompile that either. With nothing to do, it simply exits. If you open
up the <em>src/main.rs</em> file, make a trivial change, then save it and build again,
you’ll only see two lines of output:</p>
<pre><code class="language-text">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs
</code></pre>
<p>These lines show Cargo only updates the build with your tiny change to the
<em>src/main.rs</em> file. Your dependencies haven’t changed, so Cargo knows it can
reuse what it has already downloaded and compiled for those. It just rebuilds
your part of the code.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#the-cargolock-file-ensures-reproducible-builds" id="the-cargolock-file-ensures-reproducible-builds"><h4>The <em>Cargo.lock</em> File Ensures Reproducible Builds</h4></a>
<p>Cargo has a mechanism that ensures you can rebuild the same artifact every time
you or anyone else builds your code: Cargo will use only the versions of the
dependencies you specified until you indicate otherwise. For example, what
happens if next week version <code>v0.3.15</code> of the <code>rand</code> crate comes out and
contains an important bug fix but also contains a regression that will break
your code?</p>
<p>The answer to this problem is the <em>Cargo.lock</em> file, which was created the
first time you ran <code>cargo build</code> and is now in your <em>guessing_game</em> directory.
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 <em>Cargo.lock</em> file. When you build your project in the future, Cargo will
see that the <em>Cargo.lock</em> 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 <code>0.3.14</code> until you explicitly upgrade, thanks to the <em>Cargo.lock</em>
file.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#updating-a-crate-to-get-a-new-version" id="updating-a-crate-to-get-a-new-version"><h4>Updating a Crate to Get a New Version</h4></a>
<p>When you <em>do</em> want to update a crate, Cargo provides another command, <code>update</code>,
which will:</p>
<ol>
<li>Ignore the <em>Cargo.lock</em> file and figure out all the latest versions that fit
your specifications in <em>Cargo.toml</em>.</li>
<li>If that works, Cargo will write those versions to the <em>Cargo.lock</em> file.</li>
</ol>
<p>But by default, Cargo will only look for versions larger than <code>0.3.0</code> and
smaller than <code>0.4.0</code>. If the <code>rand</code> crate has released two new versions,
<code>0.3.15</code> and <code>0.4.0</code>, you would see the following if you ran <code>cargo update</code>:</p>
<pre><code class="language-text">$ cargo update
Updating registry `https://github.com/rust-lang/crates.io-index`
Updating rand v0.3.14 -> v0.3.15
</code></pre>
<p>At this point, you would also notice a change in your <em>Cargo.lock</em> file noting
that the version of the <code>rand</code> crate you are now using is <code>0.3.15</code>.</p>
<p>If you wanted to use <code>rand</code> version <code>0.4.0</code> or any version in the <code>0.4.x</code>
series, you’d have to update the <em>Cargo.toml</em> file to look like this instead:</p>
<pre><code class="language-toml">[dependencies]
rand = "0.4.0"
</code></pre>
<p>The next time you run <code>cargo build</code>, Cargo will update the registry of crates
available and reevaluate your <code>rand</code> requirements according to the new version
you specified.</p>
<p>There’s a lot more to say about <a href="http://doc.crates.io">Cargo</a><!-- ignore --> and <a href="http://doc.crates.io/crates-io.html">its
ecosystem</a><!-- ignore --> that Chapter 14 will discuss, but for
now, that’s all you need to know. Cargo makes it very easy to reuse libraries,
so Rustaceans are able to write smaller projects that are assembled from a
number of packages.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#generating-a-random-number" id="generating-a-random-number"><h3>Generating a Random Number</h3></a>
<p>Let’s start <em>using</em> <code>rand</code>. The next step is to update <em>src/main.rs</em>, as shown
in Listing 2-3:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">extern crate rand;
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
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);
}
</code></pre>
<p><span class="caption">Listing 2-3: Code changes needed in order to generate a
random number</span></p>
<p>We’re adding a <code>extern crate rand;</code> line to the top that lets Rust know we’ll be
using that external dependency. This also does the equivalent of calling <code>use rand</code>, so now we can call anything in the <code>rand</code> crate by prefixing it with
<code>rand::</code>.</p>
<p>Next, we’re adding another <code>use</code> line: <code>use rand::Rng</code>. <code>Rng</code> is a trait that
defines methods that random number generators implement, and this trait must be
in scope for us to use those methods. Chapter 10 will cover traits in detail.</p>
<p>Also, we’re adding two more lines in the middle. The <code>rand::thread_rng</code> 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 <code>gen_range</code> method on the random number
generator. This method is defined by the <code>Rng</code> trait that we brought into
scope with the <code>use rand::Rng</code> statement. The <code>gen_range</code> method takes two
numbers as arguments and generates a random number between them. It’s inclusive
on the lower bound but exclusive on the upper bound, so we need to specify <code>1</code>
and <code>101</code> to request a number between 1 and 100.</p>
<p>Knowing which traits to use and which functions and methods to call from a
crate isn’t something that you’ll just <em>know</em>. Instructions for using a crate
are in each crate’s documentation. Another neat feature of Cargo is that you
can run the <code>cargo doc --open</code> command that will build documentation provided
by all of your dependencies locally and open it in your browser. If you’re
interested in other functionality in the <code>rand</code> crate, for example, run <code>cargo doc --open</code> and click <code>rand</code> in the sidebar on the left.</p>
<p>The second line that we added to the code prints the secret number. This is
useful while we’re developing the program to be able to test it, but we’ll
delete it from the final version. It’s not much of a game if the program prints
the answer as soon as it starts!</p>
<p>Try running the program a few times:</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 7
Please input your guess.
4
You guessed: 4
$ cargo run
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 83
Please input your guess.
5
You guessed: 5
</code></pre>
<p>You should get different random numbers, and they should all be numbers between
1 and 100. Great job!</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number" id="comparing-the-guess-to-the-secret-number"><h2>Comparing the Guess to the Secret Number</h2></a>
<p>Now that we have user input and a random number, we can compare them. That
step is shown in Listing 2-4:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
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);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
}
</code></pre>
<p><span class="caption">Listing 2-4: Handling the possible return values of
comparing two numbers</span></p>
<p>The first new bit here is another <code>use</code>, bringing a type called
<code>std::cmp::Ordering</code> into scope from the standard library. <code>Ordering</code> is
another enum, like <code>Result</code>, but the variants for <code>Ordering</code> are <code>Less</code>,
<code>Greater</code>, and <code>Equal</code>. These are the three outcomes that are possible when you
compare two values.</p>
<p>Then we add five new lines at the bottom that use the <code>Ordering</code> type:</p>
<pre><code class="language-rust ignore">match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
</code></pre>
<p>The <code>cmp</code> method compares two values and can be called on anything that can be
compared. It takes a reference to whatever you want to compare with: here it’s
comparing the <code>guess</code> to the <code>secret_number</code>. <code>cmp</code> returns a variant of the
<code>Ordering</code> enum we brought into scope with the <code>use</code> statement. We use a
<a href="ch06-02-match.html"><code>match</code></a><!-- ignore --> expression to decide what to do next based on
which variant of <code>Ordering</code> was returned from the call to <code>cmp</code> with the values
in <code>guess</code> and <code>secret_number</code>.</p>
<p>A <code>match</code> expression is made up of <em>arms</em>. An arm consists of a <em>pattern</em> and
the code that should be run if the value given to the beginning of the <code>match</code>
expression fits that arm’s pattern. Rust takes the value given to <code>match</code> and
looks through each arm’s pattern in turn. The <code>match</code> construct and patterns
are powerful features in Rust that let you express a variety of situations your
code might encounter and helps ensure that you handle them all. These features
will be covered in detail in Chapter 6 and Chapter 18, respectively.</p>
<p>Let’s walk through an example of what would happen with the <code>match</code> expression
used here. Say that the user has guessed 50, and the randomly generated secret
number this time is 38. When the code compares 50 to 38, the <code>cmp</code> method will
return <code>Ordering::Greater</code>, because 50 is greater than 38. <code>Ordering::Greater</code>
is the value that the <code>match</code> expression gets. It looks at the first arm’s
pattern, <code>Ordering::Less</code>, but the value <code>Ordering::Greater</code> does not match
<code>Ordering::Less</code>, so it ignores the code in that arm and moves to the next arm.
The next arm’s pattern, <code>Ordering::Greater</code>, <em>does</em> match
<code>Ordering::Greater</code>! The associated code in that arm will execute and print
<code>Too big!</code> to the screen. The <code>match</code> expression ends because it has no need to
look at the last arm in this particular scenario.</p>
<p>However, the code in Listing 2-4 won’t compile yet. Let’s try it:</p>
<pre><code class="language-text">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
error[E0308]: mismatched types
--> src/main.rs:23:21
|
23 | match guess.cmp(&secret_number) {
| ^^^^^^^^^^^^^^ expected struct `std::string::String`, found integral variable
|
= note: expected type `&std::string::String`
= note: found type `&{integer}`
error: aborting due to previous error
Could not compile `guessing_game`.
</code></pre>
<p>The core of the error states that there are <em>mismatched types</em>. Rust has a
strong, static type system. However, it also has type inference. When we wrote
<code>let guess = String::new()</code>, Rust was able to infer that <code>guess</code> should be a
<code>String</code> and didn’t make us write the type. The <code>secret_number</code>, on the other
hand, is a number type. A few number types can have a value between 1 and 100:
<code>i32</code>, a 32-bit number; <code>u32</code>, an unsigned 32-bit number; <code>i64</code>, a 64-bit
number; as well as others. Rust defaults to an <code>i32</code>, which is the type of
<code>secret_number</code> unless we add type information elsewhere that would cause Rust
to infer a different numerical type. The reason for the error is that Rust will
not compare a string and a number type.</p>
<p>Ultimately, we want to convert the <code>String</code> the program reads as input into a
real number type so we can compare it to the guess numerically. We can do
that by adding the following two lines to the <code>main</code> function body:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
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()
.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!"),
}
}
</code></pre>
<p>The two new lines are:</p>
<pre><code class="language-rust ignore">let guess: u32 = guess.trim().parse()
.expect("Please type a number!");
</code></pre>
<p>We create a variable named <code>guess</code>. But wait, doesn’t the program
already have a variable named <code>guess</code>? It does, but Rust allows us to
<em>shadow</em> the previous value of <code>guess</code> with a new one. This feature is often
used in similar situations in which you want to convert a value from one type
to another type. Shadowing lets us reuse the <code>guess</code> variable name rather than
forcing us to create two unique variables, like <code>guess_str</code> and <code>guess</code> for
example. (Chapter 3 covers shadowing in more detail.)</p>
<p>We bind <code>guess</code> to the expression <code>guess.trim().parse()</code>. The <code>guess</code> in the
expression refers to the original <code>guess</code> that was a <code>String</code> with the input in
it. The <code>trim</code> method on a <code>String</code> instance will eliminate any whitespace at
the beginning and end. <code>u32</code> can only contain numerical characters, but the
user must press the <span class="keystroke">enter</span> key to satisfy
<code>read_line</code>. When the user presses <span class="keystroke">enter</span>, a
newline character is added to the string. For example, if the user types <span
class="keystroke">5</span> and presses <span class="keystroke"> enter</span>,
<code>guess</code> looks like this: <code>5\n</code>. The <code>\n</code> represents “newline,” the enter key.
The <code>trim</code> method eliminates <code>\n</code>, resulting in just <code>5</code>.</p>
<p>The <a href="../../std/primitive.str.html#method.parse"><code>parse</code> method on strings</a><!-- ignore --> parses a string into some
kind of number. Because this method can parse a variety of number types, we
need to tell Rust the exact number type we want by using <code>let guess: u32</code>. The
colon (<code>:</code>) after <code>guess</code> tells Rust we’ll annotate the variable’s type. Rust
has a few built-in number types; the <code>u32</code> seen here is an unsigned, 32-bit
integer. It’s a good default choice for a small positive number. You’ll learn
about other number types in Chapter 3. Additionally, the <code>u32</code> annotation in
this example program and the comparison with <code>secret_number</code> means that Rust
will infer that <code>secret_number</code> should be a <code>u32</code> as well. So now the
comparison will be between two values of the same type!</p>
<p>The call to <code>parse</code> could easily cause an error. If, for example, the string
contained <code>A👍%</code>, there would be no way to convert that to a number. Because it
might fail, the <code>parse</code> method returns a <code>Result</code> type, much like the
<code>read_line</code> method does as discussed earlier in “Handling Potential Failure
with the Result Type”. We’ll treat this <code>Result</code> the same way by
using the <code>expect</code> method again. If <code>parse</code> returns an <code>Err</code> <code>Result</code> variant
because it couldn’t create a number from the string, the <code>expect</code> call will
crash the game and print the message we give it. If <code>parse</code> can successfully
convert the string to a number, it will return the <code>Ok</code> variant of <code>Result</code>,
and <code>expect</code> will return the number that we want from the <code>Ok</code> value.</p>
<p>Let’s run the program now!</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 0.43 secs
Running `target/guessing_game`
Guess the number!
The secret number is: 58
Please input your guess.
76
You guessed: 76
Too big!
</code></pre>
<p>Nice! Even though spaces were added before the guess, the program still figured
out that the user guessed 76. Run the program a few times to verify the
different behavior with different kinds of input: guess the number correctly,
guess a number that is too high, and guess a number that is too low.</p>
<p>We have most of the game working now, but the user can make only one guess.
Let’s change that by adding a loop!</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#allowing-multiple-guesses-with-looping" id="allowing-multiple-guesses-with-looping"><h2>Allowing Multiple Guesses with Looping</h2></a>
<p>The <code>loop</code> keyword gives us an infinite loop. Add that now to give users more
chances at guessing the number:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
loop {
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()
.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!"),
}
}
}
</code></pre>
<p>As you can see, we’ve moved everything into a loop from the guess input prompt
onward. Be sure to indent those lines another four spaces each, and run the
program again. Notice that there is a new problem because the program is doing
exactly what we told it to do: ask for another guess forever! It doesn’t seem
like the user can quit!</p>
<p>The user could always halt the program by using the keyboard shortcut
<span class="keystroke">ctrl-C</span>. But there’s another way to escape this
insatiable monster that we mentioned in the <code>parse</code> discussion in “Comparing the
Guess to the Secret Number”: if the user enters a non-number answer, the program
will crash. The user can take advantage of that in order to quit, as shown here:</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 59
Please input your guess.
45
You guessed: 45
Too small!
Please input your guess.
60
You guessed: 60
Too big!
Please input your guess.
59
You guessed: 59
You win!
Please input your guess.
quit
thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:785
note: Run with `RUST_BACKTRACE=1` for a backtrace.
error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)
</code></pre>
<p>Typing <code>quit</code> actually quits the game, but so will any other non-number input.
However, this is suboptimal to say the least. We want the game to automatically
stop when the correct number is guessed.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#quitting-after-a-correct-guess" id="quitting-after-a-correct-guess"><h3>Quitting After a Correct Guess</h3></a>
<p>Let’s program the game to quit when the user wins by adding a <code>break</code>:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
loop {
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()
.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!");
break;
}
}
}
}
</code></pre>
<p>By adding the <code>break</code> line after <code>You win!</code>, the program will exit the loop
when the user guesses the secret number correctly. Exiting the loop also means
exiting the program, because the loop is the last part of <code>main</code>.</p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#handling-invalid-input" id="handling-invalid-input"><h3>Handling Invalid Input</h3></a>
<p>To further refine the game’s behavior, rather than crashing the program when
the user inputs a non-number, let’s make the game ignore a non-number so the
user can continue guessing. We can do that by altering the line where <code>guess</code> is
converted from a <code>String</code> to a <code>u32</code>:</p>
<pre><code class="language-rust ignore">let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
</code></pre>
<p>Switching from an <code>expect</code> call to a <code>match</code> expression is how you generally
move from crash on error to actually handling the error. Remember that <code>parse</code>
returns a <code>Result</code> type, and <code>Result</code> is an enum that has the variants <code>Ok</code> or
<code>Err</code>. We’re using a <code>match</code> expression here, like we did with the <code>Ordering</code>
result of the <code>cmp</code> method.</p>
<p>If <code>parse</code> is able to successfully turn the string into a number, it will return
an <code>Ok</code> value that contains the resulting number. That <code>Ok</code> value will match the
first arm’s pattern, and the <code>match</code> expression will just return the <code>num</code> value
that <code>parse</code> produced and put inside the <code>Ok</code> value. That number will end up
right where we want it in the new <code>guess</code> variable we’re creating.</p>
<p>If <code>parse</code> is <em>not</em> able to turn the string into a number, it will return an
<code>Err</code> value that contains more information about the error. The <code>Err</code> value
does not match the <code>Ok(num)</code> pattern in the first <code>match</code> arm, but it does match
the <code>Err(_)</code> pattern in the second arm. The <code>_</code> is a catchall value; in this
example, we’re saying we want to match all <code>Err</code> values, no matter what
information they have inside them. So the program will execute the second arm’s
code, <code>continue</code>, which means to go to the next iteration of the <code>loop</code> and ask
for another guess. So effectively, the program ignores all errors that <code>parse</code>
might encounter!</p>
<p>Now everything in the program should work as expected. Let’s try it by running
<code>cargo run</code>:</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 61
Please input your guess.
10
You guessed: 10
Too small!
Please input your guess.
99
You guessed: 99
Too big!
Please input your guess.
foo
Please input your guess.
61
You guessed: 61
You win!
</code></pre>
<p>Awesome! With one tiny final tweak, we will finish the guessing game: recall
that the program is still printing out the secret number. That worked well for
testing, but it ruins the game. Let’s delete the <code>println!</code> that outputs the
secret number. Listing 2-5 shows the final code:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
</code></pre>
<p><span class="caption">Listing 2-5: Complete code of the guessing game</span></p>
<a class="header" href="ch02-00-guessing-game-tutorial.html#summary" id="summary"><h2>Summary</h2></a>
<p>At this point, you’ve successfully built the guessing game! Congratulations!</p>
<p>This project was a hands-on way to introduce you to many new Rust concepts:
<code>let</code>, <code>match</code>, methods, associated functions, using external crates, and more.
In the next few chapters, you’ll learn about these concepts in more detail.