Skip to content
GitLab
Explore
Sign in
Register
Primary navigation
Search or go to…
Project
A
a2_guessing_game
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Model registry
Operate
Environments
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
D7018E-SS-RUST
a2_guessing_game
Commits
2f1fcc49
Commit
2f1fcc49
authored
7 years ago
by
Henrik Tjäder
Browse files
Options
Downloads
Patches
Plain Diff
Extracted input handling into separate function
parent
2e6d5f9c
Branches
2a
master
Branches containing commit
No related tags found
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
src/main.rs
+71
-0
71 additions, 0 deletions
src/main.rs
with
71 additions
and
0 deletions
src/main.rs
0 → 100644
+
71
−
0
View file @
2f1fcc49
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
);
let
mut
tries_counter
:
u32
=
0
;
//println!("The secret number is: {}", secret_number);
loop
{
// Get the value from inside the Ok, else print the error
let
guess
=
match
get_input
()
{
Ok
(
num
)
=>
num
,
Err
(
e
)
=>
{
println!
(
"{}"
,
e
);
continue
;
}
};
println!
(
"You guessed: {}"
,
guess
);
tries_counter
+=
1
;
match
guess
.cmp
(
&
secret_number
)
{
Ordering
::
Less
=>
println!
(
"Too small!"
),
Ordering
::
Greater
=>
println!
(
"Too big!"
),
Ordering
::
Equal
=>
{
println!
(
"You win!"
);
println!
(
"Total number of attempts: {}"
,
tries_counter
);
break
;
}
}
println!
(
"Attempts so far: {}
\n
"
,
tries_counter
);
}
}
fn
get_input
()
->
Result
<
u32
,
String
>
{
let
mut
text_input
=
String
::
new
();
println!
(
"Please input your guess."
);
/*
Instead of using the expect,
save and return potential error
*/
let
input
=
io
::
stdin
()
.read_line
(
&
mut
text_input
);
match
input
{
Ok
(
_
)
=>
(),
Err
(
e
)
=>
return
Err
(
format!
(
"{}"
,
e
)),
}
match
text_input
.trim
()
.parse
::
<
u32
>
()
{
Ok
(
num
)
=>
return
Ok
(
num
),
Err
(
e
)
=>
{
return
Err
(
format!
(
"in parsing u32, {}"
,
e
));
}
};
}
\ No newline at end of file
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment