1.2.2.1 Testcase: List
fmt::Display
를 구조체에 구현하여 요소가 반드시 각기 순서대로 처리되는 것은 까다로운 일이다. 문제는 각 write!
마다 fmt::Result
를 생성한다는 점이다. 이에 따라 모든 Result에 대해 적합한 처리가 요구된다. Rust가 제공하는 try!
매크로가 정확히 이런 용도이다.
Implementing fmt::Display
for a structure where the elements must each be
handled sequentially is tricky. The problem is that each write!
generates a
fmt::Result
. Proper handling of this requires dealing with all the
results. Rust provides the try!
macro for exactly this purpose.
try!
를 write!
에 다음처럼 사용했다:
Using try!
on write!
looks like this:
// `wrtie!`를 시도해 그게 에러인지 식별. 만약 에러라면
// 에러를 반환하고 다른 경우는 계속.
// Try `write!` to see if it errors. If it errors, return
// the error. Otherwise continue.
try!(write!(f, "{}", value));
try!
를 유용하게 사용하면, fmt::Display
를 Vec
에 구현하는게 복잡하지 않다.
With try!
available, implementing fmt::Display
for a Vec
is
straightforward:
Activity
프로그램을 수정하여 각 벡터의 요소에 대한 순번을 함께 출력해보자. 출력은 다음과 같이 나올 것이다: Try changing the program so that the index of each element in the vector is also printed. The new output should look like this:
[0: 1, 1: 2, 2: 3]