1

我使用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行包装在单独的范围内来解决此错误,但问题仍然存在。

我不确定如何解决这个问题。代码还有其他问题吗?

4

1 回答 1

3

id是类型&str。这是指向变量的指针request。调用json_as将变量的可变引用作为参数request。这会导致错误“不能*request作为可变借用,因为它也被作为不可变借用”。

有很多方法可以解决这个问题;可能最直接的方法是使用to_owned()将 转换&strString.

于 2016-04-28T22:40:31.853 回答