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);

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

相关推荐
知识分享小能手4 分钟前
Html5学习教程,从入门到精通,HTML5 简介语法知识点及案例代码(1)
开发语言·前端·javascript·学习·前端框架·html·html5
muxue1787 分钟前
go:运行第一个go语言程序
开发语言·后端·golang
米饭好好吃.8 分钟前
【Go】Go wire 依赖注入
开发语言·后端·golang
闲猫8 分钟前
go 接口interface func (m Market) getName() string {
开发语言·后端·golang
Good Note8 分钟前
Golang的静态强类型、编译型、并发型
java·数据库·redis·后端·mysql·面试·golang
可爱de艺艺8 分钟前
Go入门之struct
开发语言·后端·golang
信徒_11 分钟前
Go 语言中的协程
开发语言·后端·golang
begei16 分钟前
飞牛os使用ddns-go配合华为云实现内网穿透
开发语言·golang·华为云
m0_7482365824 分钟前
跟据spring boot版本,查看对应的tomcat,并查看可支持的tomcat的版本范围
spring boot·后端·tomcat
web1511736022330 分钟前
Spring Boot项目中解决跨域问题(四种方式)
spring boot·后端·dubbo