Is it possible to use Box with no_std?

北慕城南 提交于 2020-01-23 19:24:11

问题


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]);
}

This does not:

#![no_std]

fn main() {
    let _: Box<[u8]> = Box::new([0; 10]);
}

(Playground)

However, looking through the Rust source code, I see Box is defined in liballoc with the warning

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.

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.)


回答1:


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]);
}

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).

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.



来源:https://stackoverflow.com/questions/37843379/is-it-possible-to-use-box-with-no-std

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!