How to enable unstable allocator_api?

I'm trying to enable the allocator_api but have not used unstable features before.

As I understand it, I need to use a nightly toolchain and at the top of my main.rs I need to add:

#![feature(allocator_api)]

However, when I build with cargo +nightly build, I get the following errors:

C:\Dev\Personal\alloc_experiments> cargo +nightly build
   Compiling alloc_experiments v0.1.0 (C:\Dev\Personal\alloc_experiments)
error: an inner attribute is not permitted in this context
  --> src\main.rs:5:1
   |
5  |   #![feature(allocator_api)]
   |   ^^^^^^^^^^^^^^^^^^^^^^^^^^
6  |
7  | / unsafe impl Allocator for &MyAllocator {
8  | |     fn allocate(
9  | |         &self,
10 | |         layout: std::alloc::Layout,
...  |
17 | |     }
18 | | }
   | |_- the inner attribute doesn't annotate this implementation
   |
   = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files
help: to annotate the implementation, change the attribute from inner to outer style
   |
5  - #![feature(allocator_api)]
5  + #[feature(allocator_api)]
   |

error[E0658]: use of unstable library feature 'allocator_api'
 --> src\main.rs:1:5
  |
1 | use std::alloc::Allocator;
  |     ^^^^^^^^^^^^^^^^^^^^^
  |
  = note: see issue #32838 <https://github.com/rust-lang/rust/issues/32838> for more information
  = help: add `#![feature(allocator_api)]` to the crate attributes to enable

... and many more for each method in the Allocator trait.

What is the correct way to enable this feature on nightly?

Looks like you put the inner attribute not in the first line of your main.rs, but in the fifth. It really must be the first statement in your file for it to work. No imports, etc. can come before an inner attribute.

:see_no_evil:

Yes, you are indeed correct. I thought it was, turns out, I forgot how to read, how to scroll and do any number of basic life skills!

Thanks for pointing out my error.

1 Like

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.