【问题标题】:How can I implement a marker trait on a struct with a lifetime?如何在具有生命周期的结构上实现标记特征?
【发布时间】:2021-05-09 08:43:30
【问题描述】:

给定一个具有生命周期的结构,我如何为它提供标记特征。

struct UserProvidedID<'a> { field: &'a str, }
impl warp::reject::Reject for UserProvidedID<'_> {}

请注意这个特征,否则我想要的,我只是想“标记”它。我不想改变生命周期语义。

【问题讨论】:

  • impl&lt;'a&gt; Foo for UserProvidedID&lt;'a&gt; {} 应该可以工作!?
  • @user2722968 我得到[Error] [E0478] lifetime bound not satisfied but lifetime parameter must outlive the static lifetime
  • pub trait Reject: fmt::Debug + Sized + Send + Sync + 'static {} 所以我认为 Reject 需要静态生命周期
  • 是的,warp::reject::Reject 不能用于借用数据。原因可能是任何实现 Reject 的类型都必须在 warp 运行时内可访问,而不仅仅是在创建它的处理程序中。

标签: struct rust traits lifetime


【解决方案1】:

definition of Reject 如下:

pub trait Reject: Debug + Sized + Send + Sync + 'static { }

注意'static,这意味着您想要实现Reject 的任何类型都需要接受'static 生命周期。所以,唯一的可能就是use the static lifetime in your struct too:

struct UserProvidedID<'a> { field: &'a str, }
impl Reject for UserProvidedID<'static> {}

这可能不是你想要的,但考虑到Reject 的定义,我认为不是你的箱子,这是你唯一的选择。

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    相关资源
    最近更新 更多