4

I'm trying to make a function that takes T: Into<Vec<u8>>, but when I try to pass an array of u8 to it, it doesn't compile even if From<&'a [T]>> is implemented by Vec:

the trait `std::convert::From<&[u8; 5]>` is not implemented for `std::vec::Vec<u8>`

Here is my code

fn is_hello<T: Into<Vec<u8>>>(s: T) {
    let bytes = b"hello".to_vec();
    assert_eq!(bytes, s.into());
}

fn main() {
    is_hello(b"hello");
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Matt
  • 53
  • 1
  • 4

2 Answers2

6

It doesn't work, because b"hello" has type &[u8; 5], which does not implement Into<Vec<u8>>. You need to pass a &[u8] slice in order for it to compile:

is_hello(&b"hello"[..]);

I recommend the following question for an explanation of the difference between a slice and an array: What is the difference between Slice and Array?.

Community
  • 1
  • 1
ljedrz
  • 20,316
  • 4
  • 69
  • 97
2

Arrays are normally coerced to slice, but sometimes there's no implicit conversion.

There are some other ways to force a coercion:

b"hello" as &[u8]
b"hello".borrow()
Tatsuyuki Ishi
  • 3,883
  • 3
  • 29
  • 41