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.
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:
the parameter type
T
may not live long enough; consider adding an explicit lifetime boundT:'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? 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.
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).
We can also make the vector class generic using templates. void push (int data): This function takes one element and inserts it at the last. Amortized time complexity is O (1). void push (int data, int index): It inserts data at the specified index. Time complexity is O (1).
Alternatively, the range constructor can be utilized to initialize the vector of structs. This method is useful when one needs to create another copy of the existing vector object. As shown in the following code sample, we declare a parr3 vector of struct Person and initialize it with the contents of the parr1 vector of the same type.
In the below example, since the vector contains custom defined Person structs, the initializer list items need to be grouped inside curly brackets and separated with colons. Note that elements of the struct are accessed using the struct.element notation and outputted to the console. Video Player is loading. This is a modal window.
Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes there may be a need of extending the array.
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.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With