【笔记】Rust的智能指针

Preface

Smart Pointers in Rust

Creating a Pointer Variable

  • Boxing: storing stack data on the heap
  • Box enables boxing operations to create a pointer variable
1
2
let regular_variable = value;
let c = Box::new(regular_variable);

Dereferencing

  • Dereferencing operation allows accessing the data pointed to by a pointer
1
*regular_variable

Manually Implementing a Box

  • If a structure implements the Deref trait, the deref() method will return a pointer to the data inside the structure
  • If a structure implements the Drop trait, when this pointer goes out of scope, the drop() method will be triggered
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
use std::ops::Deref;

struct StructName<T> {
value: T
}

impl<T> StructName<T> {
fn new(v: T) -> StructName<T> {
StructName{ value: v }
}
}

impl<T> Deref for StructName<T> {
type Target = T;

fn deref(&self) -> &T {
&self.value
}
}

impl<T> Drop for StructName<T> {
fn drop(&mut self) {
...
}
}

Creating a Pointer Variable

1
2
let regular_variable = value;
let c = StructName::new(regular_variable);

Done

References

哔哩哔哩——面向加薪学习
title: 【笔记】Rust的智能指针
categories:
- Rust学习指北
tags:
- Rust
sticky: 0
lang: en
date: 2023-09-16 15:12:36

Introduction

Smart Pointers in Rust

Creating a Pointer Variable

  • Boxing: Storing stack data on the heap
  • Using Box allows for boxing operations, creating a pointer variable
1
2
let regular_variable = value;
let c = Box::new(regular_variable);

Dereferencing

  • Obtaining data pointed to by a pointer through dereferencing operation
1
*regular_variable

Taking an Address

1
&value

Manually Implementing a Box

  • If a struct implements the Deref trait, the deref() method returns a pointer to the data inside the struct
  • If a struct implements the Drop trait, when the pointer goes out of scope, the drop() method is triggered
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
use std::ops::Deref;

struct StructName<T> {
value: T
}

impl<T> StructName<T> {
fn new(v: T) -> StructName<T> {
StructName { value: v }
}
}

impl<T> Deref for StructName<T> {
type Target = T;

fn deref(&self) -> &T {
&self.value
}
}

impl<T> Drop for StructName<T> {
fn drop(&mut self) {
...
}
}

Creating a Pointer Variable

1
2
let regular_variable = value;
let c = StructName::new(regular_variable);

Finished

References

Bilibili - Learning for Salary Increase