Rust 借用某些对象类型而不是其他对象类型?

Rust borrowing with some object types and not others?

我很难理解借用是如何运作的,而且我终其一生都无法弄清楚为什么这两种情况如此不同。起作用的部分是受 https://users.rust-lang.org/t/rust-mutability-moving-and-borrowing-the-straight-dope/22166 的启发,不起作用的部分是我试图用来自 reqwest.

Response 对象实现的。
struct Player { name: String, age: u8, description: String }
impl Player {
    fn namefn(&self) -> &String {
        &self.name
    }
}

fn immutable_borrow_nok(borrowed: &reqwest::blocking::Response) -> Result<()> {
    // println!("I am some json, I don't work {:#?}", borrowed.text()); <-- if I get uncommented I won't compile
    Ok(())
}
fn immutable_borrow(borrowed: &Player) -> Result<()> {
    println!("I am {}, I've been immutably borrowed", borrowed.namefn());
    Ok(())
}

fn main() -> Result<()>{
    let our_player = Player { name: "Jones".to_string(), age: 25, description: "Just a happy guy.".to_string() };
    immutable_borrow(&our_player);
    println!("My name is {}, and I am being used after an immutable borrow", our_player.namefn());

    let res = reqwest::blocking::Client::new().post("http://httpbin.org/anything").send()?.error_for_status()?;
    immutable_borrow_nok(&res);
    println!("I am also some json but I *do* work... {:#?}", res.text());

    Ok(())
}

如果你查看 text 方法的定义 here 你可以看到它在调用后消耗(移动)self。所以在调用 text 方法后你不能使用 Response 因为它根本不存在了。

但是在您的 immutable_borrow_nok 函数中您有一个对 Response 的引用。 immutable_borrow_nok 不拥有它。不能使用引用传递的值。所以Response不能在immutable_borrow_nok.

里面消耗(移动)

如果你真的想在 immutable_borrow_nok 中使用 text 方法,你应该这样定义它:

// Response now owned by this function
fn immutable_owned_nok(owned: reqwest::blocking::Response) -> Result<()> {
    println!("I am some json, I don't work {:#?}", borrowed.text());
    Ok(())
}

但是你应该明白,在调用 immutable_owned_nok 之后你不能再在你的代码中使用你的 Response