将u8数组的引用转换为<Vec<u8>>

4

我正在尝试编写一个函数,它接受 T: Into<Vec<u8>>,但是当我尝试将一个 u8 数组传递给它时,即使 Vec 实现了 From<&'a [T]>>,它也无法编译:

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

这是我的代码

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");
}
2个回答

6

这个不起作用,因为b"hello"的类型是&[u8; 5],它没有实现Into<Vec<u8>>。您需要传递一个&[u8]切片才能编译:

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

我推荐以下问题,用于解释切片和数组之间的区别:什么是切片和数组之间的区别?

2

数组通常会被转换为切片,但有时没有隐式的转换。

还有其他一些强制转换的方法:

b"hello" as &[u8]
b"hello".borrow()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接