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.)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.