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?
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.
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.
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!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With