请考虑以下内容:
// Just a sequence of adjacent fields of same the type
#[repr(C)]
#[derive(Debug)]
struct S<T> {
a : T,
b : T,
c : T,
d : T,
}
impl<T : Sized> S<T> {
fn new(a : T, b : T, c : T, d : T) -> Self {
Self {
a,
b,
c,
d,
}
}
// reinterpret it as an array
fn as_slice(&self) -> &[T] {
unsafe { std::slice::from_raw_parts(self as *const Self as *const T, 4) }
}
}
fn main() {
let s = S::new(1, 2, 3, 4);
let a = s.as_slice();
println!("s :: {:?}\n\
a :: {:?}", s, a);
}
- 这段代码是否具有可移植性?
- 假设一个使用 repr(C) 声明的结构体内部所有字段类型相同,能否安全地将其重新解释为数组?为什么?
repr(C)
结构体中的字段相同(大小向上舍入到对齐的下一个倍数)。 - kmdrekofn from(s: S) -> [T; 4]
?在这种情况下,std::mem::transmute
是否是正确的工具? - Jasha