Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is rand::Rng able to work in a no-std environment even when I have not set default-features = false?

Shouldn't I need to disable rand's std feature flag before being able to use it in a no_std environment?

lib.rs

#![no_std]

use rand::Rng;

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

Cargo.toml

[dependencies]

rand = "0.6.5"

I am not using #![no_std] in my main.rs though.

like image 941
sn99 Avatar asked Oct 26 '25 10:10

sn99


1 Answers

Yes, you need to disable rand's std feature in order to use it in an environment where std is unavailable. However, if std is available, not disabling the std feature will still work.

The #![no_std] changes your crate's prelude from the std prelude to the core prelude. The std prelude looks like:

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

The core prelude is the same but with core instead of std. This means that, unless you write extern crate std;, your crate doesn't depend on std directly.

However, #![no_std] has no effect on your dependencies. The Rust Reference has a relevant warning:

⚠️ Warning: Using no_std does not prevent the standard library from being linked in. It is still valid to put extern crate std; into the crate and dependencies can also link it in.

Therefore, if std is available for your target and one of your dependencies needs std, then it will be able to use it. On the other hand, if std isn't available for the target, then crates that try to use it (either implicitly or explicitly) will fail to compile.

like image 102
Francis Gagné Avatar answered Oct 29 '25 08:10

Francis Gagné