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::DisplayVec에 구현하는게 복잡하지 않다. With try! available, implementing fmt::Display for a Vec is straightforward:

use std::fmt; // Import the `fmt` module.
// `Vec` `List`
// Define a structure named `List` containing a `Vec`.
struct List(Vec<i32>);
impl fmt::Display for List {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// `self` , vec .
// Dereference `self` and create a reference to `vec`
// via destructuring.
let List(ref vec) = *self;
try!(write!(f, "["));
// `vec` `v` `count` .
// Iterate over `vec` in `v` while enumerating the iteration
// count in `count`.
for (count, v) in vec.iter().enumerate() {
// For every element except the first, add a comma
// before calling `write!`. Use `try!` to return on errors.
if count != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}", v));
}
// fmt::Result .
// Close the opened bracket and return a fmt::Result value
write!(f, "]")
}
}
fn main() {
let v = List(vec![1, 2, 3]);
println!("{}", v);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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]

See also

for, ref, Result, struct, try!, and vec!

results matching ""

    No results matching ""