Rust: Vec类型的into_boxed_slice()方法

比如,我们经常看到Vec类型,但取转其裸指针,经常会看到into_boxed_slice()方法,这是为何?

复制代码
use std::{fmt, slice};

#[derive(Clone, Copy)]
struct RawBuffer {
    ptr: *mut u8,
    len: usize,
}

impl From<Vec<u8>> for RawBuffer {
    fn from(vec: Vec<u8>) -> Self {
        let slice = vec.into_boxed_slice();
        Self {
            len: slice.len(),
            // into_raw 之后,Box 就不管这块内存的释放了,RawBuffer 需要处理释放
            ptr: Box::into_raw(slice) as *mut u8,
        }
    }
}

其实,你看标准文档,就很清楚,

复制代码
pub fn into_boxed_slice(self) -> Box<[T], A>

//Converts the vector into Box<[T]>.

//If the vector has excess capacity, its items will be moved into a newly-allocated buffer with exactly the right capacity.

也就是说,转成了Box<[T]>后,指针所指向的类型,更简短了。

复制代码
let v = vec![1, 2, 3];
let slice = v.into_boxed_slice();
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);

assert!(vec.capacity() >= 10);
let slice = vec.into_boxed_slice();
assert_eq!(slice.into_vec().capacity(), 3);

这样,从操作上来讲,更加节省内存空间。

相关推荐
用户4099322502122 分钟前
想抓PostgreSQL里的慢SQL?pg_stat_statements基础黑匣子和pg_stat_monitor时间窗,谁能帮你更准揪出性能小偷?
后端·ai编程·trae
啊森要自信10 分钟前
【GUI自动化测试】Python 自动化测试框架 pytest 全面指南:基础语法、核心特性(参数化 / Fixture)及项目实操
开发语言·python·ui·单元测试·pytest
xuejianxinokok10 分钟前
什么是代数类型 ? java为什么要添加record,Sealed class 和增强switch ?
后端·rust
洛小豆10 分钟前
Git打标签仓库看不到?她说:豆子,你又忘了加 --tags!
git·后端·github
赵谨言20 分钟前
基于python智能家居环境质量分析系统的设计与实现
开发语言·经验分享·python·智能家居
元亓亓亓33 分钟前
考研408--组成原理--day1
开发语言·javascript·考研·计组
LawsonJin36 分钟前
springboot实现微信小程序支付(服务商和普通商户模式)
spring boot·后端·微信小程序
Yurko1340 分钟前
【C语言】环境安装(图文)与介绍
c语言·开发语言·学习
仲星(._.)41 分钟前
C语言:字符函数和字符串函数
c语言·开发语言
kyle~42 分钟前
C++---向上取整
开发语言·c++