Vec< struct>之间有什么区别?和&[struct]? [英] What is the difference between Vec<struct> and &[struct]?

查看:174
本文介绍了Vec< struct>之间有什么区别?和&[struct]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己得到这样的错误:

 不匹配的类型:expected`collections :: vec :: Vec< u8&``,发现`& [u8]`(预期的结构集合:: vec :: Vec,found& -ptr)

据我所知,一个是可变的,一个不是但我不知道如何在类型之间,即采取一个& [u8] / code>,并使其成为 Vec< u8> ,反之亦然。



他们?是否与 String & str 相同

解决方案


String & str


是的。一个 Vec< T> & [T] 的所有变体。 & [T] 是一组 T 依次排列的参考在内存中(也称为切片)。它表示一个指向项目开头的项目和项目数量。引用是指您不拥有的内容,因此您可以使用的一组操作是有限的。有一个可变变体(& mut [T] ),它允许您突变切片中的项目。你不能改变片中有多少。换句话说,你不能改变片段本身。


采取& [u8] code>并使其成为 Vec


对于这个具体案例

  let s:& [u8]; //设置在某处
Vec :: from(s);

但是,这不得不在堆栈上分配内存,然后复制每个值进入该内存。它比其他方式贵,但对于某种情况可能是正确的。


反之亦然




  let v = vec![1u8,2,3]; 
let s = v.as_slice();

这基本上是免费的,因为 v 仍然拥有数据,我们只是提供一个参考。这就是为什么许多API尝试在有意义的时候采取切片。


I often find myself getting an error like this:

mismatched types: expected `collections::vec::Vec<u8>`, found `&[u8]` (expected struct collections::vec::Vec, found &-ptr)

As far as I know, one is mutable and one isn't but I've no idea how to go between the types, i.e. take a &[u8] and make it a Vec<u8> or vice versa.

What's the different between them? Is it the same as String and &str?

解决方案

Is it the same as String and &str?

Yes. A Vec<T> is the owned variant of a &[T]. &[T] is a reference to a set of Ts laid out sequentially in memory (a.k.a. a slice). It represents a pointer to the beginning of the items and the number of items. A reference refers to something that you don't own, so the set of actions you can do with it are limited. There is a mutable variant (&mut [T]), which allows you to mutate the items in the slice. You can't change how many are in the slice though. Said another way, you can't mutate the slice itself.

take a &[u8] and make it a Vec

For this specific case:

let s: &[u8]; // Set this somewhere
Vec::from(s);

However, this has to allocate memory not on the stack, then copy each value into that memory. It's more expensive than the other way, but might be the correct thing for a given situation.

or vice versa

let v = vec![1u8, 2, 3];
let s = v.as_slice();

This is basically "free" as v still owns the data, we are just handing out a reference to it. That's why many APIs try to take slices when it makes sense.

这篇关于Vec&lt; struct&gt;之间有什么区别?和&[struct]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆