Rust - Tuple, Destructuring

eslerkang·2022년 3월 10일
0

Rust

목록 보기
4/10
post-thumbnail

Tuple

Tuple is also a type of collection in rust.
Different to array and vector, it's components don't have to have same types. It means it can contain no matter what the components are.
We can easily make tuple by let tup = ();, and it is empty tuple.
Unlike array and vector, it is similar to struct, so if you want to get item of specific index, you can write like println!("{}", tup.1);

fn main() {
  let tup = (3, "sdf", vec![3, 4, 5], String::from("asdfasd")); // 3 in this tup is i32
  println!("{:?}", tup);
  // array[0], vec[3]...
  println!("{}", tup.3);
  println!("{:?}", tup.2.get(1));
}

Also if we want push different types in vector, we can use Vec<(String, i32)> cause (String, i32) is a type of tuple and Vector think it's a type that can be assigned to generic. So the result of this example is vec![("asdf".to_string(), 1234), (String::from("dddd"), 20)]

Desctructuring is pulling out items of collection, so we can make variables from collection.

fn main() {
 let vec_tup = vec![(String::from("asdf"), 21), (String::from("hey"), 1)];
  println!("{:?}", vec_tup);

  let str_tup = ("1", "2", "3445");
  let (a, b, _) = str_tup;
  println!("{}, {}", a, b);
  
  let str_arr = ["1", "2", "3445"];
  let [a, b, _] = str_arr;
  println!("{}, {}", a, b);
}

It is same as JavaScript. We can do destructuring tuple, array and vector.

profile
Surfer surfing on the dynamic flow of the world

0개의 댓글