是否可以将 Box 与 no

编程入门 行业动态 更新时间:2024-10-10 12:25:55
本文介绍了是否可以将 Box 与 no_std 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在带有 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

本文发布于:2023-11-17 10:35:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609755.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Box

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!