当前位置:网站首页>Rust 中的 Cell 共享可变指针
Rust 中的 Cell 共享可变指针
2022-04-23 05:45:00 【许野平】
Rust 中的 Cell 共享可变指针
1 初识 Cell
Cell 和 Box 功能差不多,但是它既允许多个变量共享内容,也允许在多个变量共享状态下修改内容。先看个例子:
use std::cell::Cell;
fn main() {
let x = Cell::new(123);
println!("{:?}", x);
}
------------------------------------------------------
>cargo run
Cell {
value: 123 }
2 多个可修改的引用,从多种途径修改数据
注意,变量 x 并未加 mut 修饰,下面的代码一样可以对其修改。这说明 Cell 的内部修改行为应该是采用了某种 unsafe 的形式进行的,仅从函数调用的表面形式上看不出要修改变量的行为。这样就把修改操作的检查从编译期转移到的运行期,由 Cell 的代码确定是否存在修改的冲突。
use std::cell::Cell;
fn main() {
let x = Cell::new(123);
x.set(456);
println!("{:?}", x);
}
------------------------------------------------------
>cargo run
Cell {
value: 456 }
由于没有对 x 用 mut,因此编译器会认为针对 x 的操作都是只读的,不会对潜在的修改动作在编译期间报错。
由于 rust 允许多个只读的引用,因此,Cell 等于偷偷开了个后门,允许多个不同的引用修改同一个变量内容。
use std::cell::Cell;
fn main() {
let x = Cell::new(123);
let a = &x;
let b = &x;
a.set(456);
b.set(789);
println!("{:?}", x);
}
------------------------------------------------------
>cargo run
Cell {
value: 789 }
事实上, a 和 b 都是指向 x 的可变引用,但是从表面语法上看,并不需要 mut 关键字,因此可以绕过编译器的语法检查。
3 读取内容
如果内容书可以 Copy 的,也可以用 get 方法把内容复制到其他变量。
use std::cell::Cell;
fn main() {
let x = Cell::new(123);
x.set(456);
let y = x.get();
println!("{:?}, {:?}", x, y);
}
------------------------------------------------------
>cargo run
Cell {
value: 456 }, 456
如果内容未实现 Copy 特性,则 get 方法不能使用。
use std::cell::Cell;
fn main() {
let x = Cell::new("hello".to_string());
x.set("nice".to_string());
let y = x.get();
println!("{:?}, {:?}", x, y);
}
------------------------------------------------------
>cargo run
--> src\main.rs:5:15
|
5 | let y = x.get();
| ^^^
|
::: C:\Users\xxxx\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\alloc\src\string.rs:292:1
|
292 | pub struct String {
| ----------------- doesn't satisfy `String: Copy`
版权声明
本文为[许野平]所创,转载请带上原文链接,感谢
https://yeping.blog.csdn.net/article/details/123043823
边栏推荐
- PyTorch笔记——观察DataLoader&用torch构建LeNet处理CIFAR-10完整代码
- 10.Advance Next Round
- Illustrate the significance of hashcode
- Definition of C class and method
- Addition, deletion, query and modification of data
- 20 excellent plug-ins recommended by idea
- Algèbre linéaire chapitre 1 - déterminants
- Failure to deliver XID in Seata distributed transaction project
- Programming training
- Fundamentals of SQL: first knowledge of database and SQL - installation and basic introduction - Alibaba cloud Tianchi
猜你喜欢
Import of data
Programming record - picture rotation function SciPy ndimage. Simple use and effect observation of rotate()
Framework analysis 1 Introduction to system architecture
Guaba and Computational Geometry
MySQL advanced query
Delete and truncate
Explain of MySQL optimization
Illustrate the significance of hashcode
Class loading and classloader understanding
Basic knowledge of network in cloud computing
随机推荐
Common sense of thread pool
Pytorch notes - complete code for linear regression & manual or automatic calculation of gradient code comparison
Pytorch notes - get familiar with the network construction method by building RESNET (complete code)
Paper on Image Restoration - [red net, nips16] image restoration using very deep revolutionary encoder decoder networks wi
[leetcode 383] ransom letter
电机与拖动(戚金清版)学习整理
Guaba and Computational Geometry
Advanced operation of idea debug
H. Are You Safe? Convex hull naked problem
Example of reentrant lock thread waiting to wake up
A general U-shaped transformer for image restoration
RPC must know and know
[leetcode 954] double pair array
检测技术与原理
Delete and truncate
In depth understanding of the relationship between dncblevel and noise denoising in the paper
Kalman filter and inertial integrated navigation
@Problems caused by internal dead loop of postconstruct method
Explain of MySQL optimization
[leetcode 19] delete the penultimate node of the linked list