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

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

相关推荐
rylshe13147 分钟前
在scala中sparkSQL连接mysql并添加新数据
开发语言·mysql·scala
小宋加油啊7 分钟前
Mac QT水平布局和垂直布局
开发语言·qt·macos
薯条不要番茄酱20 分钟前
【SpringBoot】从零开始全面解析Spring MVC (一)
java·spring boot·后端
MyhEhud28 分钟前
kotlin @JvmStatic注解的作用和使用场景
开发语言·python·kotlin
想睡hhh33 分钟前
c++进阶——哈希表的实现
开发语言·数据结构·c++·散列表·哈希
Clown951 小时前
Go语言爬虫系列教程(一) 爬虫基础入门
开发语言·爬虫·golang
Watermelo6171 小时前
前端如何应对精确数字运算?用BigNumber.js解决JavaScript原生Number类型在处理大数或高精度计算时的局限性
开发语言·前端·javascript·vue.js·前端框架·vue·es6
Aric_Jones3 小时前
lua入门语法,包含安装,注释,变量,循环等
java·开发语言·git·elasticsearch·junit·lua
Akiiiira3 小时前
【日撸 Java 三百行】Day 12(顺序表(二))
java·开发语言
EndingCoder3 小时前
2025年JavaScript性能优化全攻略
开发语言·javascript·性能优化