In the below program I am trying to understand the intricacies of the match
statements when mut
, &
do come in. Beyond that there is no other scope in terms of any functionality.
To figure out the type of the variable, I used the variable to call a function checkout(n:i32)
. The compiler now will complain that checkout expects i32
, but whereas the program is passing some other type. I am a newbie and this was the one way i thought we could figure out types of a variable which we don't explicitly mention.
fn checkout (k5:i32) {}
fn main() {
let k5 = "learning rust".to_string();
let k1 = Some(k5);
match &mut k1 {
Some(mut n) => {
checkout(n);
println!("the idea is {} {} ", n, n);
}
None => {}
}
}
If I compile the program, the following error message is got
error[E0308]: mismatched types
--> suds12.rs:9:35
|
9 | Some(mut n)=> {checkout(n);println!("the idea is {} {} ",n,n);},
| ^ expected `i32`, found struct `String`
The above clearly demonstrates that when mut n
is present within Some
, then the type of n
is found to be that of String
.
However if the program changes from Some (mut n)
to Some(n)
, then the type of n
is said to be &mut string
. This can be again seeing by compiling the program with Some(n) and the error message is given below
error[E0308]: mismatched types
--> suds12.rs:9:31
|
9 | Some(n)=> {checkout(n);println!("the idea is {} {} ",n,n);},
| ^ expected `i32`, found `&mut String`
Here we can easily see that n
is of type &mut String
.
Why this is so?