当前位置:网站首页>Pin details in rust
Pin details in rust
2022-06-27 07:53:00 【51CTO】
Relevant concepts
Pin<P<T>>
This is a struct, What it does is it takes P The point is T Fixed in memory , Can't move . To put it bluntly , Just can't pass safe The code gets &mut T.
Pin<P> The definition is as follows :
Unpin
This is a trait, It's defined in std::marker in , If one T: Unpin, Just explain T stay pin It can move safely , Actually, you can get &mut T.
!Unpin
Yes Unpin Take the opposite ,!Unpin The double negation of is pin. If a type contains PhantomPinned, So this type is !Unpin.
Pin<P> The implementation of the
We're just going to focus here safe Method , The key is new Method :
It can be seen that , Only P The point is T: Unpin, Can only be new a Pin<P<T>>. there T Should be pin Example , But because of T: Unpin actually T Instances of are not pin. in other words ,T It didn't come true Unpin trait when ,T Will be really pin live .
because Pin::new Method requirement T: Unpin, Usually creating one does not support Unpin Of T Of pin The method of the example is to use Box::pin Method , The definition is as follows :
for example , The custom Node structure , The following code is generated pin example :
Node It didn't come true Unpin when , adopt Pin You can't get any safe methods &mut Node, So you can't move Node example . Be careful , This is immovable Node example ,node_pined yes Pin example , It can be moved .
Of course , adopt Pin Of unsafe Method , You can still get mut Node, It can also be moved Node example , But these unsafe The operation of requires the programmer to take the risk .Pin This is described in detail in the relevant methods .
Pin Can be thought of as a limit pointer (Box<T> or &mut T) Structure , stay T: Unpin Under the circumstances ,Pin<Box<T>> and Box<T> It's similar , adopt DerefMut You can get &mut T, stay T It didn't come true Unpin Under the circumstances ,Pin<Box<T>> Only through Deref obtain &T, That is to say T By pin Live in the .
Pin This method of discarding martial arts is strange , Why would there be Pin? although Box、Rc、Arc Equal pointer types can also make instances in heap Middle fixation , But these pointers are safe The method will expose &mut T, This will lead to T Instances of are moved , Such as through std::mem::swap Method , It can also be Option::take Method , It could be Vec::set_len、Vec::resize Such method , These are safe Other methods . What these methods have in common is the need &mut Self, So as long as it is not exposed &mut Self, You can achieve pin The goal of .
Why pin?
Here's how it started Async/.Await The need for asynchronous programming .
Take a look at the following asynchronous programming code :
rustc The following code will be generated automatically during compilation , Among them AsyncFuture It will be a self referencing structure :
// The `Future` type generated by our `async { ... }` block
struct AsyncFuture {
...
fut_one: FutOne,
fut_two: FutTwo,
state: State,
}
// List of states our `async` block can be in
enum State {
AwaitingFutOne,
AwaitingFutTwo,
Done,
}
impl Future for AsyncFuture {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
...
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
Be careful Future::poll The first parameter of the method is Pin<&mut Self>, If in Future::poll Methods are similar std::mem::swap And so on , It may lead to AsyncFuture Be moved , that AsyncFuture Self reference in field It will lead to disaster .
Maybe you've noticed that , there Future::poll The code is automatically generated , You don't have to call std::mem::swap Other methods , It won't lead to AsyncFuture Be moved . It's true , If here will Future::poll The first parameter of is changed to Box<Self> perhaps &mut Self, The probability is no problem . quite a lot executor The implementation of the , It's all about requirements Future It's supporting Unpin, Because in poll There are changes in the code Self The needs of , But no errors will occur , That's why .
however , For programmer implementation Future The situation of , Here's the problem .** If poll The parameter is &mut Self, Then programmers may use safe Code ( such as std::mem::swap) Make a mistake , This is the rust The idea of secure coding conflicts with .** This is it. Pin The root cause of the introduction !
Actually , stay future 0.1 In the version ,poll The parameter of is &mut Self, as follows :
To sum up
- Pin The actual is P Pointer restrictions , stay T It didn't come true Unpin Under the circumstances , avoid P Pointer exposure
&mut Self. - Pin The introduction of Async/.Await The need for asynchronous programming , The core is
Future::poll Method parameters are required . - except
Future::poll Out of the way , Not recommended Pin, There is no need to use Pin.
边栏推荐
- [notes on c++ primer] Chapter 3 string, vector and array
- js例题打印1-100之间所有7的倍数的个数及总和
- JDBC parameterized query example
- All tutor information on one page
- University database mysql
- 野風藥業IPO被終止:曾擬募資5.4億 實控人俞蘠曾進行P2P投資
- Custom palette for ggplot2
- Online text digit recognition list summation tool
- After working in a large factory for ten years with an annual salary of 400000 yuan, I was suddenly laid off. If the company wanted to abandon you, it wouldn't leave any kindness
- Cookie encryption 6
猜你喜欢

js例题打印1-100之间所有7的倍数的个数及总和

2022 love analysis · panoramic report of it operation and maintenance manufacturers

基础知识 | js基础

Testing network connectivity with the blackbox exporter
![[Software Engineering] software engineering review outline of Shandong University](/img/38/2c783df56b50dee3bbb908f6f3e70e.png)
[Software Engineering] software engineering review outline of Shandong University

Speech signal feature extraction process: input speech signal - framing, pre emphasis, windowing, fft- > STFT spectrum (including amplitude and phase) - square the complex number - > amplitude spectru

What is a magnetic separator?

Basic knowledge | JS Foundation

JS to judge the odd and even function and find the function of circular area

淘宝虚拟产品开店教程之作图篇
随机推荐
js中判断奇偶的函数,求圆面积的函数
Futures reverse Documentary - training for traders
「短视频」临夏消防救援支队开展消防安全培训授课
js打印99乘法表
磁选机是什么?
Basic knowledge | JS Foundation
R language analyzing wine data
第6届蓝桥杯
Time function calculation efficiency of C
2022爱分析· IT运维厂商全景报告
索引+sql练习优化
JS to determine whether the result is qualified, the range is 0-100, otherwise re-enter
Origin of forward slash and backslash
JS find the number of all daffodils
Publications under nature, science and cell
若xn>0,且x(n+1)/xn>1-1/n(n=1,2,...),证明级数∑xn发散
Windows下mysql-8下载、安装、配置教程
js求所有水仙花数
Speech signal processing - concept (II): amplitude spectrum (STFT spectrum), Mel spectrum [the deep learning of speech mainly uses amplitude spectrum and Mel spectrum] [extracted with librosa or torch
L'introduction en bourse de Wild Wind Pharmaceutical a pris fin: Yu pinzeng, qui avait l'intention de lever 540 millions de RMB, a effectué un investissement P2P.