新提出的 Pin 类型的用例是什么? [英] What are the use cases of the newly proposed Pin type?

查看:62
本文介绍了新提出的 Pin 类型的用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不稳定的 Rust 中有一个新的 Pin 类型和 RFC 已经合并.据说它在传递引用方面可以改变游戏规则,但我不确定应该如何以及何时使用它.

There is a new Pin type in unstable Rust and the RFC is already merged. It is said to be kind of a game changer when it comes to passing references, but I am not sure how and when one should use it.

谁能通俗的解释一下?

推荐答案

什么是固定?

在编程中,固定 X 意味着指示 X 不要移动.

What is pinning ?

In programming, pinning X means instructing X not to move.

例如:

  • 将线程固定到 CPU 内核,以确保它始终在同一个 CPU 上执行,
  • 将对象固定在内存中,以防止垃圾收集器移动它(例如在 C# 中).

Pin type 的目的是将一个对象固定在内存中.

The Pin type's purpose is to pin an object in memory.

它可以获取一个对象的地址,并保证只要 Pin 的实例还活着,这个地址就一直有效.

It enables taking the address of an object and having a guarantee that this address will remain valid for as long as the instance of Pin is alive.

开发它的主要用例是支持生成器.

The primary usecase, for which it was developed, is supporting Generators.

生成器的想法是编写一个简单的函数,带有yield,并让编译器自动将此函数转换为状态机.生成器携带的状态是堆栈"状态.从一次调用到另一次调用都需要保留的变量.

The idea of generators is to write a simple function, with yield, and have the compiler automatically translate this function into a state machine. The state that the generator carries around is the "stack" variables that need to be preserved from one invocation to another.

Pin 旨在解决的 Generators 的主要困难在于,Generator 最终可能会存储对它们自己的数据成员之一的引用(毕竟,您可以创建对堆栈值的引用)或对最终由它们自己的数据成员拥有的对象的引用(例如,从 Box 获得的 &T).

The key difficulty of Generators that Pin is designed to fix is that Generators may end up storing a reference to one of their own data members (after all, you can create references to stack values) or a reference to an object ultimately owned by their own data members (for example, a &T obtained from a Box<T>).

这是自引用结构的一个子案例,到目前为止,它需要自定义库(以及许多unsafe).自引用结构的问题在于,如果结构移动,它包含的引用仍然指向内存.

This is a subcase of self-referential structs, which until now required custom libraries (and lots of unsafe). The problem of self-referential structs is that if the struct move, the reference it contains still points to the old memory.

Pin 显然解决了 Rust 多年的问题.作为库类型.它创造了额外的保证,只要 Pin 存在,固定值就不能移动.

Pin apparently solves this years-old issue of Rust. As a library type. It creates the extra guarantee that as long as Pin exist the pinned value cannot be moved.

因此,用法是首先创建您需要的结构体,随意返回/移动它,然后当您对它在内存中的位置感到满意时初始化固定引用.

The usage, therefore, is to first create the struct you need, return it/move it at will, and then when you are satisfied with its place in memory initialize the pinned references.

这篇关于新提出的 Pin 类型的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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