Rust-05 Vec

本文最后更新于:10 个月前

Vec

Vec is a contiguous growable array type.

1
2
3
4
pub struct Vec<T, A = Global>
where
A: Allocator,
{ ... }

Examples

We can declare a mutable/immutable Vec by Vec::new()

1
2
let mut mut_vec = Vec::new();
let vec = Vec::new();

We can also declare a vec by vec! macro

1
2
let mut mut_vec = vec![1,2,3];
let vec = vec![1,2,3];

Macro vec!

1
2
3
4
5
macro_rules! vec {
() => { ... };
($elem:expr; $n:expr) => { ... };
($($x:expr),+ $(,)?) => { ... };
}

There are two forms of this macro vec!

  • Create a Vec containing a given list of elements:
1
2
3
4
let v = vec![1, 2, 3];
assert_eq!(v[0], 1);
assert_eq!(v[1], 2);
assert_eq!(v[2], 3);
  • Create a Vec from a given element and size:
1
2
let v = vec![1; 3];
assert_eq!(v, [1, 1, 1]);

Rust-05 Vec
https://trickyrat.github.io/2022/08/07/Rust-05 Vec/
作者
trickyrat
发布于
2022年8月7日
许可协议