Vec — 동적 배열

Vec — 동적 배열

Vec<T>는 동적 크기의 배열 타입이에요. 힙(heap)에 요소를 연속적으로 저장하고, 크기를 늘리거나 줄일 수 있어요.

출처: Rust 공식 문서

본문

pub struct Vec<T, A: Allocator = Global> { /* private fields */ }

주요 메서드

pub const fn new() -> Vec<T>
pub fn with_capacity(capacity: usize) -> Vec<T>
pub fn len(&self) -> usize
pub fn is_empty(&self) -> bool
pub fn capacity(&self) -> usize
pub fn push(&mut self, value: T)
pub fn pop(&mut self) -> Option<T>
pub fn insert(&mut self, index: usize, element: T)
pub fn remove(&mut self, index: usize) -> T
pub fn append(&mut self, other: &mut Vec<T>)
pub fn clear(&mut self)
pub fn truncate(&mut self, len: usize)
pub fn extend_from_slice(&mut self, other: &[T])
pub fn as_slice(&self) -> &[T]
pub fn as_mut_slice(&mut self) -> &mut [T]

예시

let mut v = Vec::new();
v.push(1);
v.push(2);
assert_eq!(v, [1, 2]);

// 매크로로 편하게
let v2 = vec![0; 5];       // 0이 5개
let v3 = vec![1, 2, 3];

Vec<T>Deref<Target=[T]>을 구현해 슬라이스 메서드를 사용할 수 있고, Index/IndexMutv[i] 접근을 지원해요. 요소의 순서가 있는 컬렉션에서 자주 사용돼요.

더 알아보기 (Learn more)