Clone a part of a Vec<u8>

Hi all,

I'm pretty new to Rust; is there a better way to achieve constructing a new Vec from an existing Vec (self.sequencer in the example below), other than this ?

 pub fn read(&mut self, position: u64, length: u64) -> Vec<u8> {

    let mut read_vec : Vec<u8> = Vec::with_capacity(length as usize);
    for i in self.sequencer.iter().skip(
        position as usize).take(length as usize) {
      read_vec.push(i.clone());
    }
    read_vec
  }
1 Like

Use the convert feature (the From trait):

#![feature(convert)]

pub fn read(&mut self, position: u64, length: u64) -> Vec<u8> {
    Vec::from(self.sequencer[(position as usize)..((position + length) as usize))
}


Scratch that. Do what he (vvv) said.

1 Like

Hello,

Yes, there is - take a slice of appropriate size and convert it to a vector:

self.sequencer[position as usize..(position+length) as usize].to_vec()
2 Likes

On suggestion of Ryman, I changed the interface to slices; so I would no longer be copying it. The concern is that the reader cannot mutate it, but (as a newbie Rustian/Ruster) this is ensured by the compiler - I think? So if the reader wantsto mutate he would haveto duplcate it. The bencmark test at least doesn't show a regression, i mild improvement over the epxpliit copying.

Is his reasoing correc?

thanks @netvl and @stebalien ! much appreciated ! outside the read interface that indeed does the trick. cheers