Skip to content

alloc methods are available in #![no_std] when running tests, despite not being imported. #99637

Open
@ilyvion

Description

@ilyvion

I was messing around in a test in a #[no_std] crate and discovered that this code:

#![no_std]

#[test]
fn foo() {
    let b = b"hello";
    let _v = b.to_vec();
}

(playground link)

compiles, which really surprised me, because [T]::to_vec() is defined in the alloc crate, and as you can see, I don't have any extern alloc; directive. It's even more surprising in that it only works in functions marked either #[test] or #[cfg(test)]. If you put it on a regular function (just remove #[test] from above), you get the expected error:

error[E0599]: no method named `to_vec` found for reference `&[u8; 5]` in the current scope
 --> src\lib.rs:5:16
  |
5 |     let _v = b.to_vec();
  |                ^^^^^^ method not found in `&[u8; 5]`

I expected this error to also happen in #[cfg(test)], but it doesn't. This is unexpected and surprising.

What makes it even more surprising is that alloc isn't actually in scope, because if you change let _v to let _v: alloc::Vec<_> in the code above, you'll be told as much.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-libtestArea: `#[test]` / the `test` libraryC-bugCategory: This is a bug.T-libsRelevant to the library team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions