简体   繁体   English

from_raw_parts_mut如何在不同大小的类型之间转换?

[英]How is from_raw_parts_mut able to transmute between types of different sizes?

I am looking at the code of from_raw_parts_mut : 我正在查看from_raw_parts_mut的代码:

pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
    mem::transmute(Repr { data: p, len: len })
}

It uses transmute to reinterpret a Repr to a &mut [T] . 它使用transmuteRepr重新解释为&mut [T] As far as I understand, Repr is a 128 bit struct. 据我了解, Repr是一个128位的结构。 How does this transmute of differently sized types work? 不同大小类型的转换如何工作?

mem::transmute() does only work when transmuting to a type of the same size - so that means an &mut[T] slice is also the same size. mem::transmute()仅在转换为相同大小的类型时才起作用-这意味着&mut[T] slice的大小也相同。

Looking at Repr : 看着Repr

#[repr(C)]
struct Repr<T> {
    pub data: *const T,
    pub len: usize,
}

It has a pointer to some data and a length. 它具有指向某些数据和长度的指针。 This is exactly what a slice is - a pointer to an array of items (which might be an actual array, or owned by a Vec<T> , etc.) with a length to say how many items are valid. 这就是切片的确切含义-指向项数组(可能是实际数组,或由Vec<T>等拥有)的指针,其长度表示有效的项数。

The object which is passed around as a slice is (under the covers) exactly what the Repr looks like, even though the data it refers to can be anything from 0 to as many T as will fit into memory. 作为切片传递的对象(在Repr )与Repr完全一样,即使它所引用的数据可以是0到可以容纳到内存的T任何值。

In Rust, some references are not just implemented as a pointer as in some other languages. 在Rust中,某些引用不仅仅像某些其他语言一样被实现为指针。 Some types are "fat pointers". 一些类型是“胖指针”。 This might not be obvious at first since, especially if you are familiar with references/pointers in some other languages! 乍一看这可能并不明显,特别是如果您熟悉其他语言的引用/指针! Some examples are: 一些例子是:

  • Slices &[T] and &mut [T] , which as described above, are actually a pointer and length. 如上所述,切片&[T]&mut [T]实际上是指针和长度。 The length is needed for bounds checks. 边界检查需要长度。 For example, you can pass a slice corresponding to part of an array or Vec to a function. 例如,您可以将与数组或Vec一部分相对应的切片传递给函数。
  • Trait objects like &Trait or Box<Trait> , where Trait is a trait rather than a concrete type, are actually a pointer to the concrete type and a pointer to a vtable — the information needed to call trait methods on the object, given that its concrete type is not known. 诸如&TraitBox<Trait>类的Trait对象,其中Trait是一个特征而不是具体类型,实际上是指向具体类型的指针和指向vtable的指针-调用对象上的trait方法所需的信息具体类型未知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM