当前位置:网站首页>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