gpt4 book ai didi

rust - TryFrom<&[u8]> trait 中的 trait 绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 11:42:59 25 4
gpt4 key购买 nike

我正在尝试为从二进制数据(从磁盘读取)创建的一堆类型实现共同特征。大多数特征方法可以使用默认实现,只有转换等需要单独实现。我想使用 TryFrom<&[u8]>从二进制数据转换为我的类型的特征,但我不知道如何表达(在特征的上下文中)&[u8] 的生命周期和我从中创建的类型的值的生命周期不相关。这是问题的最小示例。

use std::convert::TryFrom;

struct Foo;

// Value of Foo can be created from &[u8] but it doesn't borrow anything.
impl TryFrom<&[u8]> for Foo {
type Error = ();

fn try_from(v: &[u8]) -> Result<Self, ()> {
Ok(Foo)
}
}

trait Bar<'a>
where
Self: TryFrom<&'a [u8], Error = ()>, // `&` without an explicit lifetime name cannot be used here
{
fn baz() -> Self {
let vec = Vec::new();
Self::try_from(&vec).unwrap() // ERROR: vec does not live long enough (nothing is borrowed)
}
}

替代解决方案是将转换作为特征方法,但使用通用标准特征会更好。有没有办法做到这一点? (或者我可以使用 const 泛型,但我不想依赖夜间编译器。)

最佳答案

您想要的是“排名更高的特征边界”(HRTB,或简称为 hearty boy )。它们看起来像这样:for<'a> T: 'a .这个例子只是意味着:“对于每一个可能的生命周期'aT 必须......”。在你的情况下:

trait Bar
where
Self: for<'a> TryFrom<&'a [u8], Error = ()>,

您还可以直接将该要求指定为 super 特征绑定(bind),而不是 where子句:

trait Bar: for<'a> TryFrom<&'a [u8], Error = ()> { ... }

是的,现在它只意味着 Bar 的所有实现者必须实现TryFrom<&'a [u8], Error = ()>对于所有 可能的生命周期。这就是您想要的。

Working Playground

关于rust - TryFrom<&[u8]> trait 中的 trait 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62871045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com