Search code examples
rustpattern-matchingmatchborrow-checkerownership

Reusing matched variable inside of match statement


I'm looking for a good pattern of dealing with this kind of situations. I want to proceed with further operations after checking that given variable is proper type/contains what I expect. Problem is I want to reuse matched variable.

fn proceed(stream: std::net::TcpStream) {
    // ...
}

fn main() {
    let mut stream = TcpStream::connect("127.0.0.1:7878");

    match stream {
       TcpStream => proceed(stream.unwrap()),
       Error => println!("buuuu")
   }
}

It gives me variable used after move error. Blind-fixing by creating closure with move results in more cascading errors. Is using match statement any good in this situation?


Solution

  • You can pattern match on the Ok variant of the Result:

    use std::net::TcpStream;
    
    fn proceed(stream: TcpStream) {
        todo!()
    }
    
    fn example() {
        let mut stream = TcpStream::connect("127.0.0.1:7878");
    
        match stream {
           Ok(tcp) => proceed(tcp),
           Err(err) => println!("buuuu"),
       }
    }
    

    playground