How to read (std::io::Read) from a Vec or Slice?

让人想犯罪 __ 提交于 2019-12-05 02:16:03
ideasman42

While vectors don't support std::io::Read, slices do.

There is some confusion here caused by Rust being able to coerce a Vec into a slice in some situations but not others.

In this case, an explicit coercion to a slice is needed because at the stage coercions are applied, the compiler doesn't know that Vec<u8> doesn't implement Read.


The code in the question will work when the vector is coerced into a slice, either as: read_4_bytes(&*vec_as_file) or read_4_bytes(&vec_as_file[..]).


Note:

  • When asking the question initially, I was taking &Read instead of Read. This made passing a reference to a slice fail, unless I'd passed in &&*vec_as_file which I didn't think to do.
  • Thanks to @arete on #rust for finding the solution!
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!