Rust - Arrays

eslerkang·2022년 3월 8일
0

Rust

목록 보기
1/10
post-thumbnail

Array - one of the collection types

fn main() {
  let array = ["One", "Two"]; // [&str; 2]
  let array2 = ["One", "Two", "Five"]; // [&str; 3] 
  // these two arrays(1, 2) are different type

  let array3 = ["One", "Twoo"];
  println!("Is array the same as array2? {}", array == array3);

  let array4 = [0; 640];
  println!("{:?}", array4);

  let month = ["1", "2"];
  println!("{:?}", month.get(1));
  // Option enum
  println!("{:?}", month.get(3));
}

Array at rust, we cannot add or remove values at runtime. Its lengths are fixed.

And by length, type of elements of array define the type of itself.
let array = [1, 2] // [i32; 2] and let array = [1, 2, 3] // [i32; 3] are different. So we cannot compare them.
Also only one type can be stored at an array.

We can use [0; 4] statement to create [0, 0, 0, 0]. Its same as python's [0]*4

We can use .get to safely get one of the elements, but it returns Option Enum not a value.

profile
Surfer surfing on the dynamic flow of the world

0개의 댓글