为什么懒惰的静态值声称没有实现它明确实现的特征?

Fre*_*nan 5 rust reqwest

使用以下代码(尝试使用reqwestcrate 发出HTTP请求),编译器说我的值SID_URI没有实现特性PolyfillTryInto.这里发生了什么?reqwest::Url明确地实现了私人特质reqwest::into_url::PolyfillTryInto.

#[macro_use]
extern crate lazy_static;
extern crate reqwest;

static R_EMAIL: &str = "example@example.com";
static R_PASS: &str = "password";
static API_PUBKEY: &str = "99754106633f94d350db34d548d6091a";
static API_URI: &str = "https://example.com";
static AUTH_PATH: &str = "/api/v1";

lazy_static! {
    static ref SID_URI: reqwest::Url = reqwest::Url::parse(&(API_URI.to_owned() + AUTH_PATH)).unwrap();
}

fn get_sid() -> Result<reqwest::Response, reqwest::Error> {
    let client = reqwest::Client::new();
    let params = [("ID", R_EMAIL), ("PW", R_PASS), ("KY", API_PUBKEY)];
    let q = client.post(SID_URI).form(&params).send()?;
    Ok(q)
}

fn main() {
    assert!(get_sid().is_ok());
}
Run Code Online (Sandbox Code Playgroud)
error[E0277]: the trait bound `SID_URI: reqwest::into_url::PolyfillTryInto` is not satisfied
  --> src/main.rs:19:20
   |
19 |     let q = client.post(SID_URI).form(&params).send()?;
   |                    ^^^^ the trait `reqwest::into_url::PolyfillTryInto` is not implemented for `SID_URI`
   |
   = note: required because of the requirements on the impl of `reqwest::IntoUrl` for `SID_URI`
Run Code Online (Sandbox Code Playgroud)

She*_*ter 17

编译器不是骗你的,你只是跳过错误信息的相关细节.这是一个自包含的例子:

#[macro_use]
extern crate lazy_static;

struct Example;
trait ExampleTrait {}
impl ExampleTrait for Example {}

lazy_static! {
    static ref EXAMPLE: Example = Example;
}

fn must_have_trait<T>(_: T)
where
    T: ExampleTrait,
{
}

fn main() {
    must_have_trait(EXAMPLE);
    must_have_trait(42i32);
}
Run Code Online (Sandbox Code Playgroud)
error[E0277]: the trait bound `EXAMPLE: ExampleTrait` is not satisfied
  --> src/main.rs:19:5
   |
19 |     must_have_trait(EXAMPLE);
   |     ^^^^^^^^^^^^^^^ the trait `ExampleTrait` is not implemented for `EXAMPLE`
   |
   = note: required by `must_have_trait`

error[E0277]: the trait bound `i32: ExampleTrait` is not satisfied
  --> src/main.rs:20:9
   |
20 |         must_have_trait(42i32);
   |         ^^^^^^^^^^^^^^^ the trait `ExampleTrait` is not implemented for `i32`
   |
   = note: required by `must_have_trait`
Run Code Online (Sandbox Code Playgroud)

比较两个错误消息:

the trait bound `EXAMPLE: ExampleTrait` is not satisfied
the trait bound `i32: ExampleTrait` is not satisfied
Run Code Online (Sandbox Code Playgroud)

第二个错误消息并没有说42没有实现ExampleTrait,它说i32缺乏实现.此错误消息显示失败的类型,而不是值的名称!这意味着EXAMPLE在相同的上下文中指的是一种类型.

Lazy-static通过创建包含值并提供线程安全的单初始化保证的一次性类型来工作:

对于给定的static ref NAME: TYPE = EXPR;,宏生成一个唯一类型,该类型实现Deref<TYPE>并将其存储在具有名称的静态中NAME.

此包装类型不实现您的特征,只有包装类型.您将需要调用Deref然后可能重新引用它以获取a &Url,假设对a的引用Url实现了您的特征:

must_have_trait(&*EXAMPLE);
Run Code Online (Sandbox Code Playgroud)

此外,使用裸静态变量会尝试将其移出静态位置(这将是非常糟糕的事情),因此您始终需要通过引用使用它.