Archive/Rust

[Rustlings] 9. collection

Vector는 같은 타입의 데이터를 여러 개 저장할 수 있다.

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

vec1.insert(1);
vec1.insert(2);
vec1.insert(3);

for i in vec1.iter_mut() {
  *i = *i * 5;
}

HashMap은 c++의 hash나 python의 dict와 같다.

use std::collections::HashMap;

let mut hash: HashMap<String, i32> = HashMap::new();

hash.insert(String::from("apple"), 3);
hash.insert(String::from("banana"), 2);

// 해당 키가 없으면 추가
hash.entry(String::from("kiwi")).or_insert(5);
hash.entry(String::from("banana")).or_insert(7);

'Archive > Rust' 카테고리의 다른 글

[Rustlings] 11. Error Handling  (0) 2021.05.28
[Rustlings] 10. String  (0) 2021.05.26
[Rustlings] 8. module  (0) 2021.05.22
[Rustlings] 7. enum  (0) 2021.05.21
[Rustlings] 6. struct  (0) 2021.05.16