简体   繁体   English

超特征边界中的生命周期参数

[英]Lifetime parameters in supertrait bounds

I'm trying to define a trait for an object that is convertible to and from a slice of bytes.我正在尝试为 object 定义一个可转换为字节切片的特征。 I essentially want to say我本质上想说

trait Foo: AsRef<[u8]> + TryFrom<&[u8]> {}

Unfortunately, this refuses to compile unless I put a lifetime parameter on the reference, like so:不幸的是,除非我在引用上放置生命周期参数,否则它拒绝编译,如下所示:

trait Foo<'a>: AsRef<[u8]> + TryFrom<&'a [u8]> {}

This doesn't make much sense to me, because the lifetime 'a is related to the eventual try_from() call and shouldn't have to be part of the object's type.这对我来说没有多大意义,因为生命周期'a与最终的try_from()调用有关,并且不应该是对象类型的一部分。 (The implementation of try_from() copies the relevant bytes, so the lifetime of its parameter really isn't relevant.) try_from()的实现复制了相关的字节,所以它的参数的生命周期真的不相关。)

This seems like a more general issue than just slices, though;不过,这似乎是一个比切片更普遍的问题; how do you specify lifetime parameters like this for supertrait bounds?你如何为超特征边界指定这样的生命周期参数? (Apparently '_ doesn't work.) And is there a better/more idiomatic way to express this, or do I have to resort to some sort of hand-rolled custom nonsense like (显然'_不起作用。)有没有更好/更惯用的方式来表达这一点,还是我必须求助于某种手工定制的废话,比如

pub trait TryFromRef<T> { type Error; fn try_from(value: &T) -> Result<Self, Self::Error>; }

? ?

A trait bound with a lifetime parameter that holds for all lifetimes, rather than for some particular lifetime, can be specified with a so-called higher-ranked trait bound , or HRTB.一个具有生命周期参数的特征绑定,该参数适用于所有生命周期,而不是某个特定的生命周期,可以使用所谓的更高等级的特征边界或 HRTB 来指定。 In your case this might look like在您的情况下,这可能看起来像

trait Foo: AsRef<[u8]> + for<'a> TryFrom<&'a [u8]> {}

Anything implementing Foo must satisfy TryFrom<&'a u8> for any and all choices of 'a , so there's no need for a lifetime on Foo itself.任何实现Foo的东西都必须满足TryFrom<&'a u8>的任何和所有选择'a ,因此Foo本身不需要生命周期。

See also也可以看看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM