Cast &[&str] to a &[&str; 16] or fail


        let f = move |pat: &[&str]| {
            let pat = Into::<&[&str; 16]>::into(pat);

How do I make this code compile ? I want to cast a slice to a fixed size, and fail / unwrap if it errs.

There is an impl TryFrom<&[T]> for &[T; N], so you likely can just use <&[_, 16]>::try_from(pat).unwrap().

4 Likes

Ah, my failure here was:

  1. into() has to succeed

  2. my op might fail

  3. so I should have gone with try_from instead ?

Yes. Alternately, you could use TryInto, which implements the same behavior as TryFrom, but may be slightly more ergonomic for long function call chains.

1 Like