How to move one field out of a struct that implements Drop trait?

后端 未结 1 1841
轻奢々
轻奢々 2020-12-15 17:20

Here\'s an invalid Rust program (Rust version 1.1) with a function that does an HTTP client request and returns only the headers, dropping all other fields in the response.<

相关标签:
1条回答
  • 2020-12-15 17:33

    You can use std::mem::replace() to swap the field with a new blank value in order to transfer ownership to you:

    extern crate hyper;
    
    fn just_the_headers() -> Result<hyper::header::Headers, hyper::error::Error> {
        let c = hyper::client::Client::new();
        let result = c.get("http://www.example.com").send();
        match result {
            Err(e) => Err(e),
            Ok(mut response) => Ok(std::mem::replace(&mut response.headers, hyper::header::Headers::new())),
        }
    }
    
    fn main() {
        println!("{:?}", just_the_headers());
    }
    

    Here, we're replacing response.headers with a new empty set of headers. replace() returns the value that was stored in the field before we replaced it.

    0 讨论(0)
提交回复
热议问题