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

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

相关推荐
一灯架构10 小时前
90%的人答错!一文带你彻底搞懂ArrayList
java·后端
踏着七彩祥云的小丑10 小时前
pytest——Mark标记
开发语言·python·pytest
Dream of maid10 小时前
Python12(网络编程)
开发语言·网络·php
W230357657311 小时前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
Y40900111 小时前
【多线程】线程安全(1)
java·开发语言·jvm
不爱吃炸鸡柳11 小时前
Python入门第一课:零基础认识Python + 环境搭建 + 基础语法精讲
开发语言·python
minji...12 小时前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法
mldong12 小时前
Python开发者狂喜!200+课时FastAPI全栈实战合集,10大模块持续更新中🔥
后端
Dxy123931021612 小时前
Python基于BERT的上下文纠错详解
开发语言·python·bert
GreenTea12 小时前
从 Claw-Code 看 AI 驱动的大型项目开发:2 人 + 10 个自治 Agent 如何产出 48K 行 Rust 代码
前端·人工智能·后端