gpt4 book ai didi

rust - Rust 中 ZST/无人居住/单一表示类型的 MayUninit 和初始化

转载 作者:行者123 更新时间:2023-12-03 11:29:14 36 4
gpt4 key购买 nike

问题很简单,但我一直找不到答案。以下代码在 Rust 中是否有效/安全:

use core::mem::MaybeUninit;

// This is a ZST
#[derive(Debug)]
struct MyStruct;

// This is an uninhabited type
#[derive(Debug)]
enum MyEnum {}

#[derive(Debug)]
enum OneVariantEnum {
Variant1,
}

fn main() {
let s: MaybeUninit<MyStruct> = MaybeUninit::uninit();
println!("s: {:?}", unsafe { s.assume_init() });

let e: MaybeUninit<MyEnum> = MaybeUninit::uninit();
println!("e: {:?}", unsafe { e.assume_init() });

// and what about this?
let o: MaybeUninit<OneVariantEnum> = MaybeUninit::uninit();
println!("o: {:?}", unsafe { o.assume_init() });
}

最佳答案

以下似乎是正确的,因为 MyStruct是一个 ZST:

let s: MaybeUninit<MyStruct> = MaybeUninit::uninit();
println!("s: {:?}", unsafe { s.assume_init() });

然而,构造一个无人居住类型的值总是 UB,所以以下是不正确的:
let e: MaybeUninit<MyEnum> = MaybeUninit::uninit();
println!("e: {:?}", unsafe { e.assume_init() });
在 Debug模式下,Rust 可能会捕捉到这个并 panic

thread 'main' panicked at 'attempted to instantiate uninhabited type MyEnum'



至于 OneVariantEnum ,是ZST,所以类似 MyStruct以下不涉及UB:
let o: MaybeUninit<OneVariantEnum> = MaybeUninit::uninit();
println!("o: {:?}", unsafe { o.assume_init() });

关于rust - Rust 中 ZST/无人居住/单一表示类型的 MayUninit 和初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65769810/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com