Rust 中的 PhantomData 类型用法 [英] PhantomData type usage in rust

查看:41
本文介绍了Rust 中的 PhantomData 类型用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览一些 Rust 源代码,我发现了一种名为 PhantomData 的数据类型.我正在浏览 Rust 文档并在互联网上搜索了很多.但是,我无法理解这种数据类型在 rust 中的实际使用.如果可能的话,有人可以简单地解释一下吗?

I was going through some rust source code and I found a data type called PhantomData. I was going through the rust documentation and searched through the internet a lot. However, I couldn't understand the actual use of this data type with rust. If possible, could somebody please explain me this in simple manner?

pub struct GPIOD {
   _marker: PhantomData<*const ()>,
}

推荐答案

PhantomData 结构旨在向编译器发出信号,表明正在以某种对编译器透明的方式使用类型或生命周期.

The PhantomData struct is meant to signal to the compiler that a type or lifetime is being used in some way that is transparent to the compiler.

引用文档:

向您的类型添加 PhantomData 字段告诉编译器您的类型就像它存储 T 类型的值一样,即使它实际上不是.此信息用于计算某些安全属性.

Adding a PhantomData field to your type tells the compiler that your type acts as though it stores a value of type T, even though it doesn't really. This information is used when computing certain safety properties.

例如,如果我们查看切片 [T] 的迭代器类型:std::slice::Iter<'a, T>使用src按钮声明它,我们会看到它实际上被声明为如:

For example, if we look at the iterator type for a slice [T]: std::slice::Iter<'a, T> and its declaration using the src button we'll see that it's actually declared as such:

struct Iter<'a, T: 'a> {
    start: *const T,
    end: *const T,
    _phantom: PhantomData<&'a T>,
}

std 经常使用指针算法来使优化更容易获得(尽管这支持在用户代码中使用指针算法).在这种情况下,我们需要向自己保证两个原始指针(没有生命周期)指向的数据比结构体的生命周期更长,所以我们保留一个 PhantomData<&'一个 T> 告诉编译器就像 Iter 拥有一个 &'a T 一样,因此对其执行生命周期规则.

std makes frequent use of pointer arithmetic to make optimizations more readily available (Although that is not to endorse the usage of pointer arithmetic in user code). In this case, we need to assure ourselves that the data that is pointed to by the two raw pointers (Which carry no lifetimes) outlive the struct, so we keep a PhantomData<&'a T> to tell the compiler to act like as if Iter owned a &'a T therefore enforcing lifetime rules for it.

这篇关于Rust 中的 PhantomData 类型用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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