소개
이 랩에서는 언제든지 크기를 늘리거나 줄일 수 있는 Rust 의 크기 조절 가능한 배열인 벡터에 대해 배우겠습니다. 벡터는 데이터에 대한 포인터, 길이, 용량의 세 가지 매개변수를 사용하여 표현됩니다. 용량은 벡터에 대해 예약된 메모리의 양을 나타내며, 길이가 용량을 초과하면 벡터는 더 큰 용량으로 재할당됩니다. collect 메서드를 사용하여 반복자를 벡터로 수집하고, vec! 매크로를 사용하여 벡터를 초기화하고, push 메서드를 사용하여 끝에 새로운 요소를 삽입하고, len 메서드를 사용하여 요소의 수를 얻을 수 있습니다. 또한 인덱싱을 사용하여 요소에 접근하고, pop 메서드를 사용하여 마지막 요소를 제거하고, iter 또는 iter_mut 메서드를 사용하여 벡터를 반복할 수 있습니다. 또한 std::vec 모듈에는 벡터에 사용할 수 있는 더 많은 메서드가 있습니다.
참고: 랩에서 파일 이름을 지정하지 않은 경우 원하는 파일 이름을 사용할 수 있습니다. 예를 들어,
main.rs를 사용하고rustc main.rs && ./main으로 컴파일하고 실행할 수 있습니다.
벡터 (Vectors)
벡터는 크기 조절이 가능한 배열입니다. 슬라이스 (slice) 와 마찬가지로 컴파일 시간에 크기를 알 수 없지만, 언제든지 늘리거나 줄일 수 있습니다. 벡터는 다음 3 가지 매개변수를 사용하여 표현됩니다.
- 데이터에 대한 포인터 (pointer)
- 길이 (length)
- 용량 (capacity)
용량은 벡터에 대해 예약된 메모리의 양을 나타냅니다. 길이는 용량보다 작을 때까지 벡터가 증가할 수 있습니다. 이 임계값을 초과해야 할 경우, 벡터는 더 큰 용량으로 재할당됩니다.
fn main() {
// Iterators can be collected into vectors
let collected_iterator: Vec<i32> = (0..10).collect();
println!("Collected (0..10) into: {:?}", collected_iterator);
// The `vec!` macro can be used to initialize a vector
let mut xs = vec![1i32, 2, 3];
println!("Initial vector: {:?}", xs);
// Insert new element at the end of the vector
println!("Push 4 into the vector");
xs.push(4);
println!("Vector: {:?}", xs);
// Error! Immutable vectors can't grow
collected_iterator.push(0);
// FIXME ^ Comment out this line
// The `len` method yields the number of elements currently stored in a vector
println!("Vector length: {}", xs.len());
// Indexing is done using the square brackets (indexing starts at 0)
println!("Second element: {}", xs[1]);
// `pop` removes the last element from the vector and returns it
println!("Pop last element: {:?}", xs.pop());
// Out of bounds indexing yields a panic
println!("Fourth element: {}", xs[3]);
// FIXME ^ Comment out this line
// `Vector`s can be easily iterated over
println!("Contents of xs:");
for x in xs.iter() {
println!("> {}", x);
}
// A `Vector` can also be iterated over while the iteration
// count is enumerated in a separate variable (`i`)
for (i, x) in xs.iter().enumerate() {
println!("In position {} we have value {}", i, x);
}
// Thanks to `iter_mut`, mutable `Vector`s can also be iterated
// over in a way that allows modifying each value
for x in xs.iter_mut() {
*x *= 3;
}
println!("Updated vector: {:?}", xs);
}
더 많은 Vec 메서드는 std::vec 모듈에서 찾을 수 있습니다.
요약
축하합니다! 벡터 랩을 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 실력을 향상시킬 수 있습니다.