[英]Converting a reference of an array of u8 into a <Vec<u8>>
我正在尝试使用T: Into<Vec<u8>>
的函数,但是当我尝试将u8
数组传递给它时,即使From<&'a [T]>>
也无法编译它由Vec
实现:
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");
}
它不起作用,因为b"hello"
类型为&[u8; 5]
&[u8; 5]
,它没有实现Into<Vec<u8>>
。 您需要传递&[u8]
slice才能进行编译:
is_hello(&b"hello"[..]);
我建议以下问题来解释切片和数组之间的区别:切片和数组有什么区别? 。
数组通常被强制切片,但是有时没有隐式转换。
还有其他强制方式:
b"hello" as &[u8]
b"hello".borrow()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.