5

There seem to be two ways to try to turn a vector into an array, either via a slice (fn a) or directly (fn b):

use std::array::TryFromSliceError;
use std::convert::TryInto;

type Input = Vec<u8>;
type Output = [u8; 1000];

// Rust 1.47
pub fn a(vec: Input) -> Result<Output, TryFromSliceError> {
    vec.as_slice().try_into()
}

// Rust 1.48
pub fn b(vec: Input) -> Result<Output, Input> {
    vec.try_into()
}

Practically speaking, what's the difference between these? Is it just the error type? The fact that the latter was added makes me wonder whether there's more to it than that.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ændrük
  • 782
  • 1
  • 8
  • 22

1 Answers1

10

They have slightly different behavior.

The slice to array implementation will copy the elements from the slice. It has to copy instead of move because the slice doesn't own the elements.

The Vec to array implementation will consume the Vec and move its contents to the new array. It can do this because it does own the elements.

kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • Also worth noting that for the `Vec` to array implementation, on failure it returns the input array as the error. – harmic Dec 09 '20 at 05:20