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.)
no_std] is a crate-level attribute that indicates that the crate will link to the core-crate instead of the std-crate. The libcore crate in turn is a platform-agnostic subset of the std crate which makes no assumptions about the system the program will run on.
extern crate foo indicates that you want to link against an external library and brings the top-level crate name into scope (equivalent to use foo ). As of Rust 2018, in most cases you won't need to use extern crate anymore because Cargo informs the compiler about what crates are present. (
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With