在显式初始化结构成员时获取“使用可能未初始化的变量”[重复]

问题描述 投票:-2回答:1

这是我得到的错误:

error[E0381]: use of possibly uninitialized variable: `mbinfo.flags`
   --> kernel/src/loader/mod.rs:256:20
    |
256 |     mbinfo.flags = mbinfo.flags | multiboot::MULTIBOOT_INFO_CMDLINE;
    |                    ^^^^^^^^^^^^ use of possibly uninitialized `mbinfo.flags`

这是代码:

let mut mbinfo: multiboot::multiboot_info;
mbinfo.flags = 0 as u32;
mbinfo.flags = mbinfo.flags | multiboot::MULTIBOOT_INFO_CMDLINE

即使我明确初始化它,我也会收到错误。我试过让struct派生Default,但问题是struct包含了union,当我尝试派生Default时,我得到了

error: this trait cannot be derived for unions 

有什么简单的出路吗?谢谢。

多引导模块由头文件中的bindgen自动生成。

Rust Playground上的MWE,代码在最后:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=464b7fb21fc75a54618b14619076d152

rust
1个回答
2
投票
error[E0381]: assign to part of possibly uninitialized variable: `mbinfo`
    --> src/lib.rs:1178:4
     |
1178 |    mbinfo.flags = 0;
     |    ^^^^^^^^^^^^^^^^ use of possibly uninitialized `mbinfo`

编译器会告诉您确切的问题:您正在尝试使用未初始化的结构。您试图只初始化一个struct字段,Rust不允许这样做。

multiboot_info没有实现Default特性,因此您需要弄清楚如何使用其API创建它。

© www.soinside.com 2019 - 2024. All rights reserved.