简体   繁体   English

如何实现采用带有生命周期注释的通用向量的结构?

[英]How do I implement a struct that takes a generic vector with lifetime annotations?

The following compiles fine: 以下可以正常编译:

pub struct Reader<'a> {
    position: uint,
    data: &'a [u8]
}

It's a reader that takes a vector (actually a slice) of type u8 as a reference, and I specify the lifetime. 这是一个将u8类型的向量(实际上是切片)作为参考的阅读器,我指定了生存期。

However this is not exactly what I want. 但这不是我想要的。 I want to be able to make the struct generic, and to be even more precise, I want to denote that the type should be a slice of anything. 我希望能够使该结构成为泛型,并且更确切地说,我想表示该类型应该是任何东西的一部分。 I tried this for starters: 我为初学者尝试了这个:

pub struct Reader<'a, T> {
    position: uint,
    data: &'a T
}

It does not denote T to be a slice, but this is already failing with a message: 它并不表示T是切片,但这已经失败并显示一条消息:

the parameter type T may not live long enough; 参数类型T寿命可能不够长; consider adding an explicit lifetime bound T:'a ... 考虑添加显式的生命周期限制T:'a ...

Ok so I just had to specify the lifetime. 好的,所以我只需要指定生命周期。

But now my problem is that how do I make it generic of type slice and have the lifetime? 但是现在我的问题是如何使它成为普通的slice类型并具有生命周期? I tried things like Reader<'a, T: 'a Vec> and T: 'a [T] but I have no idea how I am supposed to denote this and the official guide does not seem to deal with a case like this. 我尝试了Reader<'a, T: 'a Vec>T: 'a [T]类的事情Reader<'a, T: 'a Vec>但我不知道该如何表示,而且官方指南似乎并未处理这种情况。

I simply want to construct a Reader that takes in any type of slice by borrowing it, and provides methods to operate on the data (in read-only ways). 我只是想构造一个Reader,通过借用它来获取任何类型的切片,并提供对数据进行操作的方法(以只读方式)。

After trying a bit more, I finally figured it out: 经过更多尝试后,我终于明白了:

pub struct Reader<'a, T: 'a> {
    position: uint,
    data: &'a [T]
}

This defines the reader's data to be of type Slice<T> ( [] denotes the slice) and &'a specifies the lifetime for the borrowed data. 这将读取器的data定义为Slice<T>类型( []表示切片), &'a指定借入数据的生存期。

Now I can implement stuff like this: 现在,我可以实现以下内容:

impl<'a, T> Reader<'a, T> {
    pub fn from_data(bytes: &'a[T]) -> Reader<'a, T> {
        Reader {
            position: 0,
            data: bytes
        }
    }
}

Not intending to answer directly, it's just that I came across this SO answer when I was looking for an answer to my own problem: How to apply a generic type constraint and a lifetime constraint to a struct's field. 我无意直接回答,只是我在寻找自己的问题的答案时遇到了这个SO答案:如何将通用类型约束和生命周期约束应用于结构的字段。

(Here's the working solution I came up with.) (这是我想出的可行解决方案。)

use std::io::Writer;

// This specifies lifetime constraint of 'a
// Type W must implement the Writer trait
// Type W has the lifetime 'a (the same as the related struct instance)
pub struct Foo<'a, W: 'a + Writer> {
    writer: &'a mut W
}

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

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