如何在 Rust 中实现 C 灵活数组成员模式? [英] How to implement the C flexible array member pattern in Rust?
问题描述
我想实现这个使用灵活数组成员(在 Rust 中有时称为 结构黑客):
struct test {
int key;
int dataSize;
int data[];
};
struct test* t = malloc(sizeof(struct test) + sizeOfData)
结构末尾的空数组允许您一次性分配元字段和数据.不幸的是,我不知道如何在 Rust 中做这样的事情.
The empty array at the end of structure allows you to allocate your meta fields and data all at once. Unfortunately, I can't figure out how to do such thing in Rust.
推荐答案
该结构的 Rust 等价物将使用切片:
The Rust equivalent of this struct would use a slice:
struct test {
key: i32,
dataSize: i32,
data: [i32],
}
然而,这些类型目前使用起来并不方便,因为没有安全的方法来构造它们.
however, these types are not really convenient to use at the moment as there is no safe way to construct them.
更实用的方法是使用泛型:
A more practical way to do this is to use a generic:
struct test<T: ?Sized> {
key: i32,
dataSize: i32,
data: T,
}
然后确保仅在 T
是数组或切片(只能通过强制创建)时才使用 test
.
and then to make sure that you only use test
when T
is an array or a slice (which you could only create through coercion).
另见:
这篇关于如何在 Rust 中实现 C 灵活数组成员模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!