当前位置:网站首页>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.
边栏推荐
- 什么是浮选机?
- 【批处理DOS-CMD命令-汇总和小结】-批处理命令中的参数%0、%1、%2、%[0-9]、%0-9和批处理命令参数位置切换命令shift,dos命令中操作符%用法
- No matter how good LCD and OLED display technologies are, they cannot replace this ancient display nixie tube
- 野風藥業IPO被終止:曾擬募資5.4億 實控人俞蘠曾進行P2P投資
- 2、项目使用的QT组件
- Remote connection raspberry pie in VNC Viewer Mode
- 无论LCD和OLED显示技术有多好,都无法替代这个古老的显示数码管
- Error in idea connection database
- JS uses the while cycle to calculate how many years it will take to grow from 1000 yuan to 5000 yuan if the interest rate for many years of investment is 5%
- 语音信号处理-概念(一):时谱图(横轴:时间;纵轴:幅值)、频谱图(横轴:频率;纵轴:幅值)--傅里叶变换-->时频谱图【横轴:时间;纵轴:频率;颜色深浅:幅值】
猜你喜欢

JS, and output from small to large

(笔记)Anaconda-Navigator闪退解决方法

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.

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

js用while循环计算假如投资多年的利率为5%,试求从1000块增长到5000块,需要花费多少年

Cookie encryption 7 fidder analysis phase

JS to determine whether the result is qualified, the range is 0-100, otherwise re-enter

PayPal账户遭大规模冻结!跨境卖家如何自救?

盲測調查顯示女碼農比男碼農更優秀

win命令行中导入、导出数据库相关表
随机推荐
语音信号处理-概念(一):时谱图(横轴:时间;纵轴:幅值)、频谱图(横轴:频率;纵轴:幅值)--傅里叶变换-->时频谱图【横轴:时间;纵轴:频率;颜色深浅:幅值】
win命令行中导入、导出数据库相关表
JS to print prime numbers between 1-100 and calculate the total number of optimized versions
ACM course term summary
[paper reading] internally semi supervised methods
c的时间函数算效率
(resolved) the following raise notimplementederror occurs when Minet tests
[Kevin's third play in a row] is rust really slower than C? Further analyze queen micro assessment
淘宝虚拟产品开店教程之作图篇
Index +sql exercise optimization
1-4 进制表示与转换
log4j:WARN No such property [zipPermission] in org.apache.log4j.RollingFileAppender.
【13. 二进制中1的个数、位运算】
JS use the switch statement to output the corresponding English day of the week according to 1-7
If xn > 0 and X (n+1) /xn > 1-1/n (n=1,2,...), Prove that the series Σ xn diverges
参考 | 升级 Win11 移动热点开不了或者开了连不上
Common operation and Principle Exploration of stream
JDBC reads MySQL data list
盲测调查显示女码农比男码农更优秀
[10. difference]