rust - 如何修复“无法移出 `std::cell::Ref<'_,servo_url::ServoUrl>` 的取消引用”编译错误并关闭
问题描述
我正在为 Servo 做 PR,我正在尝试确定请求 URL 是否与响应标头中提供的 URL 列表共享一个来源。我正在尝试使用在 URL 列表上的 fold 调用中运行的闭包来确定这一点。闭包需要使用请求 URL,但 rustc 抱怨请求 URL 没有复制特征。
为了解决这个问题,我尝试克隆 URL,然后将其放入 RefCell,然后从那里借用它,但现在我得到了当前错误,我不知道如何解决它。
let url = request.current_url();
//res is the response
let cloned_url = RefCell::new(url.clone());
let req_origin_in_timing_allow = res
.headers()
.get_all("Timing-Allow-Origin")
.iter()
.map(|header_value| {
ServoUrl::parse(header_value.to_str().unwrap())
.unwrap()
.into_url()
})
.fold(false, |acc, header_url| {
acc || header_url.origin() == cloned_url.borrow().into_url().origin()
});
确切的编译器错误
error[E0507]: cannot move out of dereference of `std::cell::Ref<'_, servo_url::ServoUrl>`
--> components/net/http_loader.rs:1265:70
|
1265 | .fold(false, |acc, header_url| acc || header_url.origin() == cloned_url.borrow().into_url().origin());
| ^^^^^^^^^^^^^^^^^^^ move occurs because value has type `servo_url::ServoUrl`, which does not implement the `Copy` trait
解决方案
into_*()
函数,例如按照into_url()
惯例获取所有权self
,这意味着它们会销毁(或回收)它们的输入,而不会留下任何东西。
有了.borrow()
你,你只能看到价值,但不能破坏它。
因此,要么调用.clone()
以获取您自己的副本以传递给into_url()
,或者如果您可以使用借来的值,请尝试as_url()
借用而不是破坏原件。