Why this code works?



fn main(){
    let mut  z =vec!(String::from("4"),);
   
    
    println!("{:?}",z);
    
    match z{
        _=>{println!("s")}
        
    }
    println!("{:?}",z);
}


1.at match statement it take ownership of z variable right.
But why this works

Hey,
No, match z won't take ownership of z. Even if you had made the call println!("{:?}",z) in the match arm you still would have able to use z after the match statement. However, in the following example the ownership of z is moved to z2 so this won't not compile.

fn main(){
    let z =vec!(String::from("4"),);
   
    
    println!("{:?}",z);
    
    match z{
        _=> {
            let z2 = z;
            println!("{:?}", z2);
        }
        
    }
    println!("{:?}",z);
}

The _ identifier in Rust is special because it does not bind values. It means that any assignment to _ (even in a match pattern) will not move the value. Try renaming the variable to something else, even _z, and it will move the Vec as you initially expected:

fn main() {
    let x = vec!(String::from("Hello"));

    match x {
        _x => (),
    }

    // This will fail, because `_x` took ownership of `x`.
    println!("{:?}", x);
}

Secondly, you can turn a binding pattern into a reference with the ref keyword:

fn main() {
    let x = vec!(String::from("Hello"));

    match x {
        ref _x => (),
    }

    // This works fine, because `_x` only references `x`.
    println!("{:?}", x);
}

Or by explicitly borrowing:

fn main() {
    let x = vec!(String::from("Hello"));

    match &x {
        _x => (),
    }

    // This works fine, because `_x` only references `x`.
    println!("{:?}", x);
}
11 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.