Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use vec! macro in a #![no_std] library?

Tags:

rust

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?

like image 840
Matthias Wimmer Avatar asked Jul 25 '18 10:07

Matthias Wimmer


People also ask

How do you initialize VEC?

In order to initialize a vector via the new() method call, we use the double colon operator: let mut vec = Vec::new(); This call constructs a new, empty Vec<T> . The vector will not allocate until elements are pushed onto it.

How do you initialize a vector in Rust?

Using Vec::new() Method: let v : Vec<i64> = Vec::new(); Here v is the initialized vector that will contain the 64-bit integer datatype. It is initialized with help of the Vec::new() method.


2 Answers

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!

like image 63
hellow Avatar answered Oct 05 '22 10:10

hellow


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;
}
like image 34
Tim Diekmann Avatar answered Oct 05 '22 12:10

Tim Diekmann