Try_into() borrowed array

use std::convert::TryInto;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let v = vec![0u8; 20];
    takes_borrowed_array(v.try_into()?);
    Ok(())
}

fn takes_borrowed_array(hash: &[u8; 20]) { }
error[E0277]: the trait bound `&[u8; 20]: From<Vec<u8>>` is not satisfied
 --> src/main.rs:6:28
  |
6 |     takes_borrowed_array(v.try_into()?);
  |                            ^^^^^^^^ the trait `From<Vec<u8>>` is not implemented for `&[u8; 20]`
  |
  = note: required because of the requirements on the impl of `Into<&[u8; 20]>` for `Vec<u8>`
  = note: required because of the requirements on the impl of `TryFrom<Vec<u8>>` for `&[u8; 20]`
  = note: required because of the requirements on the impl of `TryInto<&[u8; 20]>` for `Vec<u8>`

I guess I'm missing some conversion, but which one?

You need to call as_slice() first. This is because the impl you're looking for is From<&[u8]> for &[u8; 20]

fn main() -> Result<(), Box<dyn Error>> {
    let v = vec![0u8; 20];
    takes_borrowed_array(v.as_slice().try_into()?);
    Ok(())
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.