1 rust
我正在为 Servo 开发 PR,并尝试确定请求 URL 是否与响应标头中提供的 URL 列表共享源。我试图使用在 URL 列表上的折叠调用内运行的闭包来确定这一点。闭包需要使用请求 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()
});
Run Code Online (Sandbox Code Playgroud)
确切的编译器错误
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
Run Code Online (Sandbox Code Playgroud)
into_*()函数,例如into_url()按照惯例,拥有 的所有权self,这意味着它们销毁(或回收)其输入,不留下任何东西。
只.borrow()允许你看到价值,但不能破坏它。
因此,要么调用.clone()以获取您自己的副本以传递给into_url(),要么如果您可以使用借用的值,请尝试as_url()借用而不是销毁原始值。