not_empty_vec

Macro not_empty_vec 

Source
macro_rules! not_empty_vec {
    () => { ... };
    ($elem:expr; 0) => { ... };
    ($elem:expr; 0usize) => { ... };
    ($elem:expr; $n:expr) => { ... };
    ($($x:expr),+ $(,)?) => { ... };
}
Available on crate features alloc or std only.
Expand description

Creates a NonEmptyVec containing the arguments.

§Panics

When using the not_empty_vec! macro in the form of not_empty_vec![E; N], if N is a non-literal expression that resolves to 0, the program will panic only when debug_assertions is enabled.

If it is a literal 0, a compiler error is still thrown as expected.

§Examples

Create a NonEmptyVec containing a given list of elements:

use not_empty::{not_empty_vec, NonEmptyVec};

let vec: NonEmptyVec<_> = not_empty_vec![1, 2, 3];
assert_eq!(vec[0], 1);
assert_eq!(vec[1], 2);
assert_eq!(vec[2], 3);

Create a NonEmptyVec from a given element and size:

use not_empty::{not_empty_vec, NonEmptyVec};

let vec: NonEmptyVec<_> = not_empty_vec![1; 3];
assert_eq!(vec, [1, 1, 1]);

Note: Unlike array expressions, this syntax supports all elements which implement Clone and the number of elements doesn’t have to be constant.

Because it will use Clone::clone to duplicate an expression, you should be careful using this with types having a nonstandard Clone implementation. For example, not_empty_vec![Rc::new(1); 5] will create a vector of five references to the same boxed integer value, not five references pointing to independently boxed integers.

Unlike std::vec!, all of the following cases are compiler errors:

// error: cannot initialize non-empty vector with zero length
not_empty::vec![1; 0];
// error: cannot initialize non-empty vector with zero length
not_empty::vec![1; 0usize];
// error: cannot initialize non-empty vector with zero length
not_empty::vec![];

And, as stated previously, with debug_assertions enabled, not_empty_vec! will panic if initialized with a length of zero at runtime:

let n = 0;

// panic: non-empty vector initialized with an empty vector
not_empty::vec![10; n];