【发布时间】:2022-01-17 21:28:15
【问题描述】:
我正在使用 Rust 开发 Teensy 4.0 (--target thumbv7em-none-eabihf),这意味着我必须使用 #![no_std]。
在某些情况下,我想根据旋转开关的位置做不同的事情。
以下是一个玩具示例,说明了我想要返回实现特征的一系列对象之一的问题。
fn text_for(selector: i32) -> impl Fn()->Box<dyn Iterator<Item=char>> {
match selector {
1 => || {
let rval : Box<dyn Iterator<Item=char>> = Box::new("author".chars());
rval
},
_ => || {
let rval : Box::<dyn Iterator<Item=char>> = Box::new(b"baseline".iter().map(|&b| (b) as char));
rval
}
}
}
很遗憾,Box 在 no_std 环境中不可用。我看到了对 alloc 板条箱 (Is it possible to use Box with no_std?) 的引用,但是当我使用 extern crate alloc; use alloc::boxed::Box; 时,编译器会抱怨
error: no global memory allocator found but one is required; link to std or add `#[global_allocator]` to a static item that implements the GlobalAlloc trait.
error: `#[alloc_error_handler]` function required, but not found.
note: Use `#![feature(default_alloc_error_handler)]` for a default error handler.
按照 lkolbly 的建议,尝试使用 alloc-cortex-m 板条箱将 CortexMHeap 用作 #[global_allocator] 会导致以下错误
error[E0554]: `#![feature]` may not be used on the stable release channel
--> /home/thoth/.cargo/registry/src/github.com-1ecc6299db9ec823/linked_list_allocator-0.8.11/src/lib.rs:1:41
|
1 | #![cfg_attr(feature = "const_mut_refs", feature(const_mut_refs))]
| ^^^^^^^^^^^^^^^^^^^^^^^
如何使用 stable rust 在 no_std 环境中处理 dyn 特征实例?
【问题讨论】:
-
错误消息表明您在拉入分配箱后没有设置分配错误处理程序。你试过这样做吗?
-
要使用 Box,您可以自己制作一个全局分配器,也可以使用像 github.com/rust-embedded/alloc-cortex-m/blob/master/examples/… 这样的库来制作一个全局分配器
-
docs.rs/alloc-cortex-m/latest/alloc_cortex_m "注意,使用它作为全局分配器需要夜间 Rust。"
-
您可以使用其他分配器。在lib.rs/keywords/allocator查看分配器列表。