【问题标题】:Converting a reference of an array of u8 into a <Vec<u8>>将 u8 数组的引用转换为 <Vec<u8>>
【发布时间】:2017-04-13 11:21:41
【问题描述】:

我正在尝试创建一个采用T: Into&lt;Vec&lt;u8&gt;&gt; 的函数,但是当我尝试将u8 的数组传递给它时,即使From&lt;&amp;'a [T]&gt;&gt;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");
}

【问题讨论】:

    标签: arrays generics rust traits


    【解决方案1】:

    它不起作用,因为b"hello" 有类型&amp;[u8; 5],它没有实现Into&lt;Vec&lt;u8&gt;&gt;。您需要传递 &amp;[u8] 切片才能编译:

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

    我推荐以下问题来解释切片和数组之间的区别:What is the difference between Slice and Array?

    【讨论】:

      【解决方案2】:

      数组通常被强制切片,但有时没有隐式转换。

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

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

      【讨论】:

        猜你喜欢
        • 2020-10-28
        • 1970-01-01
        • 2021-07-31
        • 2021-03-27
        • 1970-01-01
        • 2021-03-18
        • 1970-01-01
        • 1970-01-01
        • 2020-06-06
        相关资源
        最近更新 更多