TicketStore에 Indexing을 추가하는 것을 할 것이다.
Index trait을 implement하여 할 수 있는데,
Index trait은 Rust의 standard library에 정의되어 있다.
// Slightly simplified
pub trait Index<Idx>
{
type Output;
// Required method
fn index(&self, index: Idx) -> &Self::Output;
}
- index type을 나타내는 하나의 generic parameter Idx와
- index를 통해 반환받는 type을 나타내는 하나의 associated type Output이 있다.
index method가 Option을 return하지 않는 방식에 이유가 궁금하면,
array와 vec indexing에서와 같이,
이상한 곳을 access하려하면 index는 panic을 일으키는 것을 생각하면 된다.
13_Index의 exercise를 진행했다.
TicketStore의 Index trait을 implement하는 것이었다.
index자리에 올 type을 정의하고,
반환한 type도 정의했다.
vec에 index자리에 올 type은 usize여야하므로 TicketId를 usize로 변환하는 method를
implement해줬다.

그랬더니 test를 잘 통과한 것을 확인할 수 있다.
Index는 read-only다.
그래서 mutable하게 쓰려면, IndexMut trait을 구현하면 된다.
// Slightly simplified
pub trait IndexMut<Idx>: Index<Idx>
{
// Required method
fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
}
추가적인 기능을 활성화하는 것이기 때문에,
IndexMut은 type이 Index를 implement할 때, 사용할 수 있다.
14_index_mut exercise는 IndexMut trait을 implement하는 것이었다.
&mut Ticket을 받아오는 method가 없어 implement했고
이 과정에서 어려움이 많았다.
iterator를 이용하여 id가 같은 것을 찾을 때,
iterator도 mutable로 해야 &mut ticket을 받아올 수 있었다.
그리고 index를 접근할 때도, 미리 정의한 get_mut를 사용해 할 수 있구나~~ 생각했다.

굳이 TicketId를 usize로 안바꿔도 된다는 사실을 깨달았다.
'Rust Programming' 카테고리의 다른 글
| [Rust] 7. Threads (0) | 2024.10.12 |
|---|---|
| [Rust] 6. HashMap, BTreeMap (0) | 2024.10.07 |
| [Rust] 6. Ticket Management: Slices, Mutable slices, Two states (0) | 2024.10.02 |
| [Rust] 6. Ticket Management: Combinators, impl Trait (0) | 2024.08.09 |
| [Rust] 6. Ticket Management: Iterators, Iter, Lifetimes (0) | 2024.08.07 |