Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between TryFrom<&[T]> and TryFrom<Vec<T>>?

Tags:

rust

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.

like image 599
ændrük Avatar asked Jan 24 '23 14:01

ændrük


1 Answers

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.

like image 165
kmdreko Avatar answered Jan 29 '23 11:01

kmdreko