当前位置:网站首页>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
边栏推荐
- Stanford machine learning course summary
- undefined reference to `Nabo::NearestNeighbourSearch
- ES6 face test questions (reference documents)
- ROS package NMEA_ navsat_ Driver reads GPS and Beidou Positioning Information Notes
- positioner
- Re regular expression
- idea中安装YapiUpload 插件将api接口上传到yapi文档上
- C1小笔记【任务训练篇二】
- Jenkspy package installation
- .105Location
猜你喜欢
SSD硬盘SATA接口和M.2接口区别(详细)总结
positioner
re正則錶達式
2022 Jiangxi Photovoltaic Exhibition, China distributed Photovoltaic Exhibition, Nanchang solar energy utilization Exhibition
Calculation of fishing net road density
QTableWidget使用讲解
Fashion classification case based on keras
2022江西光伏展,中國分布式光伏展會,南昌太陽能利用展
ArcGIS table to excel exceeds the upper limit, conversion failed
解决报错max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
随机推荐
Secure credit
Logic regression principle and code implementation
The JS timestamp of wechat applet is converted to / 1000 seconds. After six hours and one day, this Friday option calculates the time
Scikit learn sklearn 0.18 official document Chinese version
Special effects case collection: mouse planet small tail
Build openstack platform
re正则表达式
Go的Gin框架学习
Operation of 2022 mobile crane driver national question bank simulation examination platform
Summary of floating point double precision, single precision and half precision knowledge
Classes and objects
Identification verification code
A few lines of code teach you to crawl lol skin pictures
_ FindText error
MySQL auto start settings start with systemctl start mysqld
Climbing watermelon video URL
The method of changing a value in the array and a value in the object of wechat applet
ArcGIS license error -15 solution
Flash operates on multiple databases
C1 notes [task training chapter I]