我想在带有 no_std 的板条箱中使用 Box.这可能吗?到目前为止,我的简单尝试都没有奏效.
I'd like to use Box in a crate with no_std. Is this possible? My simple attempts so far have not worked.
这会编译(但使用标准库):
This compiles (but uses the standard library):
fn main() { let _: Box<[u8]> = Box::new([0; 10]); }这不会:
#![no_std] fn main() { let _: Box<[u8]> = Box::new([0; 10]); }(游乐场)
然而,查看 Rust 源代码,我看到 Box 是在 liballoc 中定义的,带有警告
However, looking through the Rust source code, I see Box is defined in liballoc with the warning
这个库和 libcore 一样,不是用于一般用途,而是作为其他库的构建块.本库中的类型和接口是通过标准库重新导出的,不应通过本库使用.
This library, like libcore, is not intended for general usage, but rather as a building block of other libraries. The types and interfaces in this library are reexported through the standard library, and should not be used through this library.
由于 Box 不依赖于 std 而只是为它重新导出,看来我只需要找出将其导入我的代码的正确方法.(尽管这似乎是不推荐的.)
Since Box doesn't depend on std but is only reexported for it, it seems like I only need to figure out the right way to import it into my code. (Despite this seeming to be not recommended.)
推荐答案你必须导入 alloc 箱子:
You have to import the alloc crate:
#![no_std] extern crate alloc; use alloc::boxed::Box; fn main() { let _: Box<[u8]> = Box::new([0; 10]); }alloc crate 是编译器提供的(就像在非 no_std 环境中的 std 一样),所以你不需要拉它来自 crates.io 或在 Cargo.toml 中指定.自 Rust 1.36(稳定 PR)以来,板条箱是稳定的.
The alloc crate is compiler-provided (just as std in non-no_std environments), so you don't need to pull it from crates.io or specify it in Cargo.toml. The crate is stable since Rust 1.36 (stabilization PR).
请注意,这会编译为 lib,但由于缺少 lang_items 而不会编译为二进制文件.不幸的是,编译 no_std 二进制文件仍然需要每晚使用 Rust.
Note that this compiles as a lib, but not as binary because of missing lang_items. Compiling a no_std binary unfortunately still requires Rust nightly.
更多推荐
是否可以将 Box 与 no
发布评论