14

In standard Rust code, the vec! macro is in the prelude and there is no need to make it visible manually. I'm working on a library that doesn't use the standard library and sets #![no_std], so also the prelude isn't visible.

Inside the test code, I am using functionality from the standard library, therefore I have a

#[cfg(test)]
extern crate std;

This works without problems to access functions and datatypes from the standard library, but now I would like to access the vec!(...) macro and I don't know how.

use std::vec::vec!; results in an error:

expected one of `::`, `;`, or `as` here 

at the position of the exclamation mark.

How can I access this macro instead?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Matthias Wimmer
  • 3,789
  • 2
  • 22
  • 41

2 Answers2

10

In addition to Tims answer, if you have an embedded system and you have an allocator, but not std, you can use

#[macro_use]
extern crate alloc;

to be able to use vec!

Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69
hellow
  • 12,430
  • 7
  • 56
  • 79
  • Do you have any pointer on how I do this exactly? Indeed my platform has `malloc()` and `free()` available. Is there some standard implementation of `GlobalAlloc` or a crate that implements it based on these two functions? Because else rustc complains, that it doesn't find a `#[alloc_error_handler]` function. – Matthias Wimmer Jul 25 '18 at 11:33
  • I'm not quite sure, but it shouldn't be that hard to do it on your own. Just call (via FFI) your malloc and free and implemented the [needed Trait](https://doc.rust-lang.org/core/alloc/trait.GlobalAlloc.html). – hellow Jul 25 '18 at 11:40
  • 1
    @MatthiasWimmer maybe something like https://play.rust-lang.org/?gist=fbe68c0a4b50c109ea637a53d136202c&version=nightly&mode=debug&edition=2015 – hellow Jul 25 '18 at 11:48
  • @the8472 I'm note sure, if you can use it as an allocator. Yes, you can use the functions on your own, but vec/string/etc need the global allocator. – hellow Jul 26 '18 at 05:39
3

vec! is a macro so you have to add #[macro_use]:

#[cfg(test)]
#[macro_use]
extern crate std;

If you are on a nightly compiler, you can also use the use_extern_macros feature:

#![feature(use_extern_macros)]

#[cfg(test)]
extern crate std;

#[cfg(test)]
mod test {
    use std::vec;
}
Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69