假设我们有一个结构,其所有字段都具有相同大小的类型:
struct Homogeneous {
a: u64,
b: u64,
c: u64,
d: u64
}
Run Code Online (Sandbox Code Playgroud)
我们有一种“安全”的方法来从字节数组构造它:
impl From<[u8; 32]> for Homogeneous {
fn from(slice: [u8; 32]) -> Self {
// helper macro to convert slice of u8s into u64
macro_rules! to_u64 {
($slice: expr, $at: expr) => {{
let ss = &$slice[$at..$at + 8];
let mut buf = [0u8; 8];
buf.copy_from_slice(&ss);
u64::from_ne_bytes(buf)
}};
}
Self {
a: to_u64!(bytes, 0),
b: to_u64!(bytes, 8),
c: to_u64!(bytes, 16),
d: to_u64!(bytes, 24),
}
}
}
Run Code Online (Sandbox Code Playgroud)
这一切都很好并且有效。问题是不安全的解决方案(使用 …
我目前正在学习Rust编程语言,并且在阅读了有关所有权和生存期概念(我发现它是GC的优雅替代品)之后,我找不到以下问题的答案。就所有权和生存期而言,以下代码按注释说明工作。
fn main() {
let mut x: u32 = 10; // x is pointing to memory in stack
println!("before reassignment: x = {}", x); // prints 10
x = 11; // memory in stack simply has been updated with another value
println!("after reassignment: x = {}", x); // prints 11
} // x is dropped here
Run Code Online (Sandbox Code Playgroud)
每个人都很高兴,但请想象我们是否有这样的代码:
fn main() {
let mut x = Box::new([99; 1000]); // x owns a Box, which owns heap allocated array
println!("before reassignment: x[0] = …Run Code Online (Sandbox Code Playgroud)