Reputation: 7317
Reading a Rust tutorial I found the following code snippet:
let f = File::open("hello.txt");
let mut f = match f {
Ok(file) => file,
Err(e) => return Err(e)
};
This seems that f
could have the value of type Result<_, _>
(if f == Err(e)
) or a value of type _
(i.e., whatever type file
happens to be).
So does this mean that match expressions in Rust are type indeterminate?
Upvotes: 2
Views: 123
Reputation: 1375
No, types aren't indeterminate. You are first creating a binding of type Result<io::File, io::Error>
. Then, you are creating a new (mutable) binding for f
of type io::File
(because that's what is contained in the Ok
variant of the Result
enum in your case) This new binding shadows the old one, just like a a block in, say, Perl (and C/C++ etc.) would introduce a new scope:
my $x = [42, 24];
{
# new scope
my $x = $x->[0];
say Dumper $x; # 42, an INT
}
say Dumper $x; # [42, 24], an ARRAY
In Rust, let
can be thought of as introducing a new scope similarly, shadowing the previous binding.
Since you also return
out of your function when you encounter an Err(_)
, the compiler is still able to infer the type of the second binding f
to be io::File
.
Upvotes: 5