我使用nickel.rs在Rust中编写了一个端点:
{
let client = client.clone();
let mongodb = MongoRepository::new(client, "rust-users".into());
router.put("/users/:id",middleware!(|request, mut response| {
let id = try_with!(response, {
request.param("id")
.ok_or((StatusCode::BadRequest, "Id parameter required"))
});
let user = try_with!(response, {
request.json_as::<User>()
.map_err(|e|
(StatusCode::BadRequest, format!("{}",e))
)
});
let update_id = try_with!(response, {
mongodb.update_by_id("users", id, user)
.map_err(|e|
(StatusCode::InternalServerError, e)
)
});
ApiResult::Ok(StatusCode::Ok, update_id.to_json())
}));
}
在这一行:
let id = try_with!(response, {
request.param("id")
.ok_or((StatusCode::BadRequest, "Id parameter required"))
});
request
以不可变状态借用,但在这一行:
let user = try_with!(response, {
request.json_as::<User>()
.map_err(|e|
(StatusCode::BadRequest, format!("{}",e))
)
});
request 在可变状态下被借用。这会导致以下错误:
error: cannot borrow `*request` as mutable because it is also borrowed
as immutable
我试图通过将该id
行包装在单独的范围内来解决此错误,但问题仍然存在。
我不确定如何解决这个问题。代码还有其他问题吗?