Can a no_std crate have std dependencies in test cases only?

I am working on a UTF8 / UTF32 conversion crate with no_std support. Is it possible for the library itself be no_std, but the test cases be std?

How would it look like in Cargo.toml file?

You can use cfg_attr to only enable no_std outside of tests:

#![cfg_attr(not(test), no_std)]

Playground example

originally solved this with extern crate but I like this solution better

Nevermind, use

extern crate std;

Integration tests (i.e. tests in the tests/ directory) are compiled separately from your library and depend on std by default. No changes in Cargo.toml are needed.

You should not use this approach. The extern crate std; approach is a preferred one. Plus you can use extern inside test modules.


I didn't know that, for some reason I thought it had to be at the root of the crate

In practice gating no_std causes unpleasant issues related to prelude, especially if your crate has an std or alloc feature. Previously I was proponent of gating no_std, but after hitting several such issues I see the merit of using extern crate std. It's easier to think about crate code when std and alloc are explicit dependencies.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.