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

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

相关推荐
就是帅我不改12 小时前
揭秘Netty高性能HTTP客户端:NIO编程的艺术与实践
后端·面试·github
Ray6612 小时前
SugLucene索引构建
后端
舒一笑12 小时前
Saga分布式事务框架执行逻辑
后端·程序员·设计
Emma歌小白13 小时前
完整后台模块模板
后端
得物技术13 小时前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
Emma歌小白13 小时前
配套后端(Node.js + Express + SQLite)
后端
isysc113 小时前
面了一个校招生,竟然说我是老古董
java·后端·面试
uhakadotcom13 小时前
静态代码检测技术入门:Python 的 Tree-sitter 技术详解与示例教程
后端·面试·github
幂简集成explinks13 小时前
e签宝签署API更新实战:新增 signType 与 FDA 合规参数配置
后端·设计模式·开源