0

Let's assume I have the following slice (code does not compile):

struct Data {
  data: Vec<u8>
}

impl Data {

  pub fn parse_ipv4(&self) -> Ipv4Addr {
    let octets: [u8; 4] = self.data[2..6]; // this does not compile
    Some(Ipv4Addr::from(octets));
  }
}

The problem is that the compiler cannot infer the usize of the slice of data, so how do I explicitly tell it the length of the new array?

crockpotveggies
  • 12,682
  • 12
  • 70
  • 140
  • Does this answer your question? [How to get a slice as an array in Rust?](https://stackoverflow.com/questions/25428920/how-to-get-a-slice-as-an-array-in-rust) – Brian61354270 Feb 09 '20 at 03:43

1 Answers1

0

The key is TryInto. It looks like you meant to return Option<Ipv4Addr> so I added that in.

use std::net::Ipv4Addr;
use std::convert::TryInto;

struct Data {
    data: Vec<u8>
}

impl Data {
    pub fn parse_ipv4(&self) -> Option<Ipv4Addr> {
        let octets: Result<[u8; 4], _> = self.data[2..6].try_into();
        octets.map(Ipv4Addr::from).ok()
    }
}
Francis Gagné
  • 60,274
  • 7
  • 180
  • 155
Brady Dean
  • 3,378
  • 5
  • 24
  • 50