gpt4 book ai didi

rust - 如果我在代码的各个位置使用了非可变变量,为什么会出现借来的错误?

转载 作者:行者123 更新时间:2023-12-03 11:45:10 24 4
gpt4 key购买 nike

我正在学习rust,并且正在努力理解为什么以下代码无法在req.into_body()上编译为“Error [E0505]:由于被借用而无法移出req”错误。如果我删除了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()的返回)转换为拥有的类型。您可以通过 ToOwned::to_owned 或通过显式转换(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)
}

关于rust - 如果我在代码的各个位置使用了非可变变量,为什么会出现借来的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62813784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com