I'm fairly new to Rust so I came across this piece of code in the official Guide
let input = io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<uint> = from_str(input.as_slice());
let num = match input_num {
Some(num) => num,
None => {
println!("Please input a number!");
return;
}
};
While the understand the first two statements (on input
and inputnum
), I'm not quite sure about the match statement. So I checked the documentation which shows that Option<T>
can take two values , either None
or Some(T)
for some (object?) T
. So I tested the following code:
io::println(
match input_num {
Some(num) => "somenum",
None => {
println!("Please input a number only!");
return;
}
}
);
This code works as expected; it prints somenum
if you enter a number and otherwise it prints the error message. However, the compiler gives a warning stating: warning: unused variable:
num, #[warn(unused_variable)] on by default
. This confirmed my suspicions that the num
inside the `match is used as a variable.
Question: How is it possible that rust
does not complain about (in the Guide's example) having two variables with the same name num
? Or does it "hand over" the pointer to the inside num
to the outside num
?
Also in the case of an empty return
what exactly is returned? I'm guessing it is unit ()
because it is mentioned here that
functions without a
-> ...
implicitly have return type()
Edit: Sorry for missing the obvious point. The return
directly exits the function without bothering to put anything into num
.
P.S. I noticed that using cargo build
to compile does not give warnings the second time around (not making any changes). Does cargo
keep tracking of versions or something?