본문 바로가기
Rust

[Rust] List with Vector

by llHoYall 2022. 8. 2.

Vector is a collection type and allows us to store more than one value in a single data structure that puts all the values next to each other in memory.

Vectors can only store values of the same type.

Create Vector

To create a vector, we can use Vec::new() function or vec! macro.

If we create a vector with an initial value, Rust will infer the type of value.

let v: Vec<i32> = Vec::new();
let v = vec![1, 2, 3];

Add Element

We can use the push() method to append elements to vectors.

let mut v = Vec::new();
v.push(1);
v.push(2);
v.push(3);

Delete Element

We can use the pop() method to delete the last element from the vector.

let mut v = vec![1, 2, 3];
let elem = v.pop();
println!("{elem:?}"); // Some(3)

Get Element

There are two ways to reference a value stored in vectors.

One way is via indexing, and the other is via get() method.

let v = vec![1, 2, 3];
let v0 = &v[0];
let v1 = v.get(1);
println!("{v0}, {v1:?}"); // 1, Some(2)

They have different behavior when they try to access an index value outside the range of existing elements.

Indexing method will cause the program to panic.

get() method will return None without panicking

Iterate Element

We can iterate all elements in a vector using for loop.

let v = vec![1, 2, 3];
for i in &v {
    println!("{i}");
}

Store Multiple Types

The variants of an enum are defined under the same enum type, so when we need one type to represent elements of different types, we can define and use an enum.

enum MultipleType {
    Int(i32),
    Float(f64),
    Text(String),
}

let v = vec![
    MultipleType::Int(7),
    MultipleType::Float(3.14),
    MultipleType::Text(String::from("test")),
];

'Rust' 카테고리의 다른 글

[Rust] Enums  (0) 2022.08.06
[Rust] Struct  (0) 2022.08.04
[Rust] Function  (0) 2022.08.01
[Rust] Control Flow  (0) 2022.07.31
[Rust] Operator  (0) 2022.07.30

댓글