如果我在代码的不同位置使用非可变变量,为什么会出现借用错误?

Why a borrowed error appears if I use a non mutable variable in various place of my code?

我正在学习 Rust,我正在努力理解为什么以下代码无法编译并出现一些“错误 [E0505]:无法移出 req,因为它被借用了”req.into_body()。如果我删除 println!或者在比赛前移动它,它会运行。

async fn hello_world(req: Request<Body>) -> Result<Response<Body>, Infallible> {
  let mut response = Response::new(Body::empty());

  let method = req.method();
  let path = req.uri().path();

  match (method, path) {
    (&Method::GET, "/") => {
      *response.body_mut() = Body::from("Try POSTing data to /echo");
    }
    (&Method::POST, "/echo") => {
      *response.body_mut() = req.into_body();
    }
    _ => {
      *response.status_mut() = StatusCode::NOT_FOUND;
    }
  };
  println!("{} {}", method, path);

  Ok(response)
}

我理解一些借用,但我不明白为什么 println 的位置会发生任何变化,因为我已经定义了在匹配中成功使用的非可变变量。

你不能同时拥有可变借用和不可变借用。对于您的情况,将是将借用的类型(method()uri().path() 中的 return)转换为拥有的类型。您可以通过 ToOwned::to_owned, or via explicit conversions (playground):

async fn hello_world(req: Request<Body>) -> Result<Response<Body>, Infallible> {
    let mut response = Response::new(Body::empty());

    let method = req.method().clone(); // &Method -> Method
    let path = req.uri().path().to_string(); // &str -> String
    // `req` is not borrowed at this point, so it can be mutated

    match (method.clone(), path.as_str()) {
        (Method::GET, "/") => {
            *response.body_mut() = Body::from("Try POSTing data to /echo");
        }
        (Method::POST, "/echo") => {
            *response.body_mut() = req.into_body();
        }
        _ => {
            *response.status_mut() = StatusCode::NOT_FOUND;
        }
    };
    println!("{} {}", method, path);

    Ok(response)
}