为什么rand :: Rng能够在非标准环境中工作,即使我没有设置default-features = false?

问题描述 投票:2回答:1

在能够在disable rand's std feature flag环境中使用之前,我不应该需要no_std吗?

礼拜.人生

#![no_std]

use rand::Rng;

pub fn random_small() -> u8{
    rand::thread_rng().gen::<u8>()
}

Cargo.toml

[dependencies]

rand = "0.6.5"

我不是在我的主要人物中使用#![no_std]

rust bare-metal
1个回答
3
投票

是的,您需要禁用rand的std功能才能在std不可用的环境中使用它。但是,如果std可用,则不会禁用std功能仍然有效。

#![no_std]改变你的箱子的前奏从std前奏到core序曲。 std前奏看起来像:

extern crate std;
use std::prelude::v1::*;

core前奏是相同的,但core而不是std。这意味着,除非你写extern crate std;,你的箱子不直接依赖std

但是,#![no_std]对您的依赖项没有影响。 The Rust Reference有一个相关的警告:

⚠️警告:使用no_std不会阻止标准库被链接。将extern crate std;放入包中仍然有效,依赖关系也可以将其链接。

因此,如果std可用于您的目标,并且您的一个依赖项需要std,那么它将能够使用它。另一方面,如果std不可用于目标,那么尝试使用它的条件箱(隐式或显式)将无法编译。

© www.soinside.com 2019 - 2024. All rights reserved.