当前位置:网站首页>Box pointer of rust
Box pointer of rust
2022-04-23 18:03:00 【Xu Yeping】
Rust Of Box The pointer
1 Point to Copy Data of type
image i32 Such a simple type , Realized Copy characteristic , Usually the data is stored in stack space . Take a simple example , See how to use Box Pointers encapsulate such data :
fn main() {
let x: Box<i32> = Box::new(123);
let y: i32 = *x;
println!("{:?}, {:?}", x, y);
}
---------------------------------
>cargo run
123, 123
Box The function of is to turn the packed data into a pointer . Rust It's similar in C Bare pointer to language , Very unsafe . Usually we use Box Realize the function of pointer , Ensure code security .
We can also modify it Box Point to :
fn main() {
let mut x: Box<i32> = Box::new(123);
*x = 456;
println!("{:?}", x);
}
This is related to C Pointers in languages are almost the same .
2 Point to Move Data of type
image String This type of data , It didn't come true Copy characteristic , Usually the data is stored in heap space . Take a simple example , See how to use Box Pointers encapsulate such data :
fn main() {
let x = String::from("Hello!");
let y = Box::new(x);
let z = *y;
println!("{:?}, {:?}, {:?}", x, y, z);
}
---------------------------------
>cargo run
let x = String::from("Hello!");
| - move occurs because `x` has type `String`, which does not implement the `Copy` trait
3 | let y = Box::new(x);
| - value moved here
4 | let z = *y;
5 | println!("{:?}, {:?}, {:?}", x, y, z);
| ^ value borrowed here after move
Compilation error . as a result of ,x It didn't come true Copy characteristic ,let y = Box::new(x); hold x Value move In Box. therefore , hinder println command , No more printing x The value of the .
fn main() {
let x = String::from("Hello!");
let y = Box::new(x);
let z = *y;
println!("{:?}, {:?}", y, z);
}
---------------------------------
>cargo run
--> src\main.rs:5:28
|
3 | let y = Box::new(x);
| - move occurs because `y` has type `Box<String>`, which does not implement the `Copy` trait
4 | let z = y;
| - value moved here
5 | println!("{:?}, {:?}", y, z);
| ^ value borrowed here after move
Get rid of x, Still make mistakes . as a result of let z = *y; hold Box Packaged String value move To z 了 . Switch to let z = y; Is the same , For this reference rust Dereference mechanism .
Continue to modify :
fn main() {
let x = String::from("Hello!");
let y = Box::new(x);
println!("{:?}", y);
}
---------------------------------
>cargo run
"Hello!"
This time, Ok 了 !
3 Box The value of
Look at an example of linked list node design :
struct Node {
data: i32,
next: Option<Node>,
}
fn main() {
let x = Node {
data: 123,
next: None,
};
let y = Box::new(x);
println!("{:?}", y);
}
---------------------------------
>cargo run
--> src\main.rs:1:1
|
1 | struct Node {
| ^^^^^^^^^^^ recursive type has infinite size
2 | data: i32,
3 | next: Option<Node>,
| ------------ recursive without indirection
Compiler hints that recursive definitions need to be implemented in an indirect way . Because I use it directly Option<Node> , because Node Recursive definitions exist in , Its size cannot be determined ( It could actually be infinity ). therefore , Need to use a pointer instead of Node. The code is modified as follows :
#[derive (Debug)]
struct Node {
data: i32,
next: Option<Box<Node>>,
}
fn main() {
let x = Node {
data: 123,
next: None,
};
let y = Box::new(x);
println!("{:?}", y);
}
---------------------------------
>cargo run
Node {
data: 123, next: None }
Very good !
because Node Contains pointers , Therefore, we can't Copy Data type of , use Box When packaging and String Types have similar characteristics .
版权声明
本文为[Xu Yeping]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230544498647.html
边栏推荐
- .104History
- Scikit learn sklearn 0.18 official document Chinese version
- Submit local warehouse and synchronize code cloud warehouse
- mysql自动启动设置用Systemctl start mysqld启动
- Realization of consumer gray scale
- ROS package NMEA_ navsat_ Driver reads GPS and Beidou Positioning Information Notes
- Notes on common basic usage of eigen Library
- Crawl lottery data
- C1小笔记【任务训练篇一】
- Timestamp to formatted date
猜你喜欢

Anchor location - how to set the distance between the anchor and the top of the page. The anchor is located and offset from the top

The JS timestamp of wechat applet is converted to / 1000 seconds. After six hours and one day, this Friday option calculates the time

C1小笔记【任务训练篇一】

positioner

Nat commun | current progress and open challenges of applied deep learning in Bioscience
![C1 notes [task training part 2]](/img/10/48f7490a6c097f2b178ae948cb2c91.png)
C1 notes [task training part 2]

Docker installation MySQL

Installation du docker redis

2022 Jiangxi Photovoltaic Exhibition, China distributed Photovoltaic Exhibition, Nanchang solar energy utilization Exhibition

Laser slam theory and practice of dark blue College Chapter 3 laser radar distortion removal exercise
随机推荐
开源按键组件Multi_Button的使用,含测试工程
An example of linear regression based on tensorflow
Using files to save data (C language)
Selenium + webdriver + chrome realize Baidu to search for pictures
Welcome to the markdown editor
Amount input box, used for recharge and withdrawal
ArcGIS table to excel exceeds the upper limit, conversion failed
Examination question bank and online simulation examination of the third batch (main person in charge) of special operation certificate of safety officer a certificate in Guangdong Province in 2022
2022江西光伏展,中国分布式光伏展会,南昌太阳能利用展
_ FindText error
Theory and practice of laser slam in dark blue College - Chapter 2 (odometer calibration)
Gaode map search, drag and drop query address
GDAL + ogr learning
C network related operations
由tcl脚本生成板子对应的vivado工程
Nanotechnology + AI enabled proteomics | Luomi life technology completed nearly ten million US dollars of financing
Solving the problem of displaying too many unique values in ArcGIS partition statistics failed
Use of list - addition, deletion, modification and query
Summary of floating point double precision, single precision and half precision knowledge
xlsxwriter. exceptions. Filecreateerror: [errno 13] permission denied