英文:
A sound way to create a default "empty" instance of a Rust struct with type parameters, which wraps a Vec<T>?
问题
以下是代码部分的翻译:
/// 这是一个简单的结构体,只是一个围绕`Vec<T>`的包装器:
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct VecSet<T: PartialOrd + Ord + PartialEq + Eq + Hash + Clone> {
pub(crate) data: Vec<T>,
}
static EMPTY_VEC_SET : VecSet<&str> = VecSet { data : vec![] };
pub(crate) fn empty_vecset<T: 'static + PartialOrd + Ord + PartialEq + Eq + Hash + Clone>() -> &'static VecSet<T> {
// 我们需要能够返回一个对空vec集的引用;因为它将是不可变的,泛型类型是无关紧要的 - 只需分配一次并根据需要返回引用
unsafe {
let ptr = &EMPTY_VEC_SET as *const VecSet<&str>;
let ptr2 = ptr as *const VecSet<T>
&*ptr2
}
}
请注意,上述代码翻译中包含了转义字符(<
和 &
),这些字符在原始代码中是HTML实体,因此需要进行转义以在代码中显示正确。
英文:
I have a simple struct which is just a wrapper around a Vec<T>
:
/// A set-like data structure uses a sorted `Vec` and binary-search.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct VecSet<T: PartialOrd + Ord + PartialEq + Eq + Hash + Clone> {
pub(crate) data: Vec<T>,
}
I need a way to return a borrow of an empty instance of that type - an instance over an empty Vec
that will never be added to, will never have a mutable reference to it created. This is a library, and the concrete type of T
is caller-defined, so there is not a finite set of possible types.
For a variety of reasons, returning Option<VecSet>
would make a fairly clunky API for callers; allocating a new instance is not an option when returning a borrow.
Allocating a new instance on demand and using, say, lazy_static
with type_map
would work, but would also be, IMHO, overkill - this is literally an object that can never have anything done with it except report its emptiness (and empty results can be returned a lot).
Borrowing a pattern that is common in Java, where object size is not a consideration, what I came up with was to statically allocate an instance over a type (&str
arbitrarily chosen),
convert it to a raw pointer, and then coerce it to the generified type - the thinking being, if it cannot have contents, there should be no code that is dependent on the size of the backing memory buffer because that will always be zero.
static EMPTY_VEC_SET : VecSet<&str> = VecSet { data : vec![] };
pub(crate) fn empty_vecset<T: 'static + PartialOrd + Ord + PartialEq + Eq + Hash + Clone>() -> &'static VecSet<T> {
// We need to be able to return a reference to an empty vec set; since it will be
// immutable, the generic type is irrelevant - allocate once and return a reference as needed
unsafe {
let ptr = &EMPTY_VEC_SET as *const VecSet<&str>;
let ptr2 = ptr as *const VecSet<T>;
&*ptr2
}
}
Is this actually sound? Is there some nuance of statics being moved I could be missing? Is there a vastly simpler way of doing this I'm just not aware of?
答案1
得分: 3
以下是代码的翻译部分:
This is not sound, as noted in the comments, for a variety of reasons:
- You cannot transmute a `Vec`, its layout is not guaranteed.
- The data pointer may not be well aligned for `T`.
However, there is no reason to reach for unsafe code - you can create a generic `const`, it's just a bit clunky. You need to use an associated const:
```rust
fn empty_vec<T>() -> &'static Vec<T> {
struct Foo<T>(T);
impl<T: 'static> Foo<T> {
const VEC: &'static Vec<T> = &Vec::new();
}
Foo::<T>::VEC
}
When inline_const
will be stabilized, this will be easier:
#![feature(inline_const)]
fn empty_vec<T>() -> &'static Vec<T> {
const { &Vec::new() }
}
<details>
<summary>英文:</summary>
This is not sound, as noted in the comments, for variety of reasons:
- You cannot transmute a `Vec`, its layout is not guaranteed.
- The data pointer may not be well aligned for `T`.
However, there is no reason to reach for unsafe code - you can create a generic `const`, it's just a bit clunky. You need to use an associated const:
```rust
fn empty_vec<T>() -> &'static Vec<T> {
struct Foo<T>(T);
impl<T: 'static> Foo<T> {
const VEC: &'static Vec<T> = &Vec::new();
}
Foo::<T>::VEC
}
When inline_const
will be stabilized, this will be easier:
#![feature(inline_const)]
fn empty_vec<T>() -> &'static Vec<T> {
const { &Vec::new() }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论