컬렉션
- 유용한 데이터 구조
- 힙에 저장되어 실행 도중 커지거나 줄어들수 있다.
벡터
i32 값을 가지는 벡터 생성
let v: Vec<i32> = Vec::new();
let v = vec![1, 2, 3];
- vec! : 제공된 값을 저장한 새로운 벡터 생성
벡터 업데이트
- push 메서드 : 요소를 추가한다.
- 가변 참조자를 사용하는 식으로 구성된다.
let mut v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);
- get 메서드 : 값 읽어오기
- 인덱스를 쓸수도 있다.
- 존재하지 않는 값을 읽어올시 프로그램이 강제종료된다.
let v = vec![1, 2, 3, 4, 5];
let third: &i32 = &v[2];
println!("The third element is {third}");
let third: Option<&i32> = v.get(2);
match third {
Some(third) => println!("The third element is {third}"),
None => println!("There is no third element."),
}
let mut v = vec![100, 32, 57];
for i in &mut v {
*i += 50;
}
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12),
];
String
- String::new(); 로 생성
- to_string() 을 통해 리터럴에서 생성
- String::from(); 으로 생성
let mut s = String::new();
let data = "initial contents";
let s = data.to_string();
// 이 메서드는 리터럴에서도 바로 작동합니다:
let s = "initial contents".to_string();
let hello = String::from("안녕하세요");
문자열 업데이트하기
- format! 매크로 혹은 + 연산자를 사용한다.
let mut s = String::from("foo");
s.push_str("bar");
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // s1은 여기로 이동되어 더 이상 사용할 수 없음을 주의하세요
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{s1}-{s2}-{s3}");
문자열 인덱싱
- 문자열엔 인덱싱을 바로 사용할수 없다.
- String은 Vec<u8> 을 감싼것이며, 한 글자가 2바이트의 길이를 가질수도 있기 때문이다.
문자열 슬리이싱
let hello = "Здравствуйте";
let s = &hello[0..4];
문자열 반복
- 개별 유니코드 반복을 위해 .chars()
- 개별 바이트의 반복을 위해 .bytes()
for c in "Зд".chars() {
println!("{c}");
}
for b in "Зд".bytes() {
println!("{b}");
}
해시맵
- 연관된 키와 값을 저장한다.
- HashMap::new() 로 생성한다.
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
값 접근하기
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
let team_name = String::from("Blue");
let score = scores.get(&team_name).copied().unwrap_or(0);
- get 메서드는 Option<&V> 를 반환
- copied 로 Option<V> 를 찾아온다.
- unwrap_or() 로 값이 없을시 0이 되게 한다.
해시맵의 소유권
- Copy 트레이트를 구현한 타입은 복사된다.
- String과 같이 소유권이 있는 값은 이동된다.
해시맵 업데이트
- 각각의 유일한 키는 연관된 값을 하나만 가진다.
- 같은 키에 다른값을 넣어 업데이트할수 있다.
키가 없을때만 추가하는 방법
- entry() API를 사용한다
- 해당 키가 존재할시 Entry 키에 연관된 값을 반환한다.
- 없을시 해당 키에 대한 새 값을 넣고 반환한다.
- 검사하려는 키를 매개변수로 받고 없을시에만 추가하게 할수 있다.
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.entry(String::from("Yellow")).or_insert(50);
scores.entry(String::from("Blue")).or_insert(50);
println!("{:?}", scores);
예전 값에 기초해 업데이트하기
use std::collections::HashMap;
let text = "hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
// 역참조
}
println!("{:?}", map);