如何在 Rust 中连接静态数组? [英] How to concatenate static arrays in rust?

查看:100
本文介绍了如何在 Rust 中连接静态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 u8 的静态数组,我将实现一个函数来连接它们.类似的东西

I have two static array of u8 and I would implement a function to concatenate them. Something like that

fn concat_u8(first: &'static [u8], second: &'static [u8]) -> &'static [u8] {
    &[&first[..], &second[..]].concat()
}

编译器显示错误返回对当前函数拥有的数据的引用.那是因为分配的内存将在函数结束时释放.

The compiler shows me the error returns a reference to data owned by the current function. That because the allocated memory will be free at the end of the function.

如何强制"生命周期为静态?

How can I "force" the lifetime to be static?

编辑

我有一个长时间运行的过程.

I've a long running process.

在开始时,进程会处理一些输入以计算结果(即 concat_u8 函数).结果是一个 u8 数组,并将在进程生命的其余部分以只读方式使用.无法在内部 start 事件"之后调用函数 concat_u8.

At start time, the process processes some input in order to calculate a result (ie concat_u8 function). The result is an array of u8 and will be used in the rest of the process life in read-only. The function concat_u8 couldn't be called after an "internal start event".

我不想使用 Box,因为动态分配意味着一些开销(可能无法衡量?)并将结果存储为 &[u8].

I'd like not to use Box because the dynamic allocation implies a little overhead (maybe not measurable?) and store the result as &[u8].

我有机会这样做吗?

我是否有机会在不使用 unsafe 块的情况下做到这一点?

Have I any chance to do that without using an unsafe block?

推荐答案

不可能在不泄漏内存的情况下将两个切片连接到一个具有静态生命周期的新切片.

It is not possible to concatenate two slices to a new slice with static lifetime without leaking memory.

切片在内存中连续存储.连接两个具有静态生命周期的切片需要将它们复制到新分配的内存中,因为结果也需要是连续的.这个新分配的内存必然归当前函数所有,所以你不能返回对它的引用.

Slices are stored consecutively in memory. Concatenating two slices with static lifetime requires copying them to newly allocated memory, since the result also needs to be consecutive. This newly allocated memory will necessarily be owned by the current function, so you cannot return a reference to it.

您必须将内存的所有权转回给调用者:

You will have to transfer ownership of the memory back to the caller instead:

pub fn concat_u8(first: &[u8], second: &[u8]) -> Vec<u8> {
    [first, second].concat()
}

不再需要要求输入具有静态生命周期,并且可能根本不需要实现这个函数,因为调用它不会比简单地内联代码更短或更清晰.

There is no need to require the inputs to have static lifetime anymore, and probably no need to implement this function at all, since calling it will be no shorter or clearer than simply inlining the code.

这篇关于如何在 Rust 中连接静态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆