关于rust:将`#![no_std]`添加到库中时,该库的用户是否有任何缺点或复杂性?

When adding `#![no_std]` to a library, are there any disadvantages or complications for the users of that library?

我写了一个Rust库。我听说了no_std功能,并注意到我的库没有使用corealloc未提供的std中的任何内容。因此,从理论上讲,我可以仅添加#![no_std]属性并更改一些导入。

但是我不知道这会对我的图书馆用户产生怎样的影响。当然,我希望通过使用#![no_std]no_std环境中的用户也可以使用我的板条箱。那当然很好。但是:我的库的用户是否由于我的库为no_std有什么不利之处?例如,他们是否被迫也使用#![no_std]?那将是不好的。我想知道,因为大多数箱子都将no_std兼容性隐藏在货运功能的后面。而且我实际上无法在线找到有关此问题的任何信息。

如果使用#![no_std]没有任何不利影响,那么每个没有std就能使用的板条箱都应该添加该属性,对吗?


For example, are they forced to also use #![no_std]?

一点也不。依赖的板条箱(即将消耗您的板条箱的板条箱/项目)将知道找到您的依赖项所需要的core板条箱,并且可以自由使用它,就像曾经涉及过no_std一样。主要区别在于对这种依赖的期望以及有多少其他板条箱可以使用它。换句话说,如果为no_std

准备了依赖关系,则与您的依赖关系兼容的板条箱集应始终是一个超集。

KodrAus / rust-nostd的自述文件(在库中使用和测试no_std的示例),还建议尽可能使用no_std以实现最大兼容性:

The current design of Rust's standard library is split into a few layers, each building on the assumed platform capabilities of the one below. There's:

  • std: the full standard library assumes the presence of threads, a filesystem, and networking. [...]
  • alloc: the collections layer builds on the core by assuming runtime support for dynamic memory allocation.
  • core: the core layer makes no (well, not very many) assumptions about the > underlying platform. Just about any target that can run Rust code is supported by core.

So when you're designing your library you can make it maximally portable by targeting the lowest layer of the standard library that you can.

某些package箱将no_std置于货运功能后面的原因是,该package箱可能包含某些选择加入功能,这些功能确实需要std或至少是alloc。通过限制货运功能,没有标准库的环境仍可以使用板条箱,而具有stdalloc的环境可以使用板条箱的扩展API。显示此功能的" lib.rs "示例可以在下面看到。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#![cfg_attr(not(feature ="std"), no_std)]

#[cfg(feature ="std")]
extern crate core;

#[cfg(feature ="alloc")]
extern crate alloc;

pub fn foo_into_slice(slice: &mut [u8]) { unimplemented!() }

/// Vec requires alloc
#[cfg(feature ="alloc")]
use alloc::vec::Vec;

#[cfg(feature ="alloc")]
pub fn foo_into_vec(vec: &mut Vec<u8>) { unimplemented!() }