Skip to content

Commit 9999ab4

Browse files
committed
Update 08 quiz solution to use Newtype pattern
1 parent 9167723 commit 9999ab4

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

quiz_solutions/08_solution.md

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,24 +44,26 @@ For now, if we wanted to print a `vec` we would have to use `{:?}` inside the pr
4444

4545
Let's attempt to implement the `Display` trait for a `vec` by implementing the required method `fmt`:
4646
```rust
47-
use std::fmt;
47+
use std::fmt::{self, Display, Formatter};
4848

49-
impl Display for Vec<u8> {
49+
struct CustomVec<T>(Vec<T>);
50+
51+
impl Display for CustomVec<u8> {
5052
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
5153
write!(f, "Values:\n")?;
52-
for v in &self {
54+
for v in &self.0 {
5355
write!(f, "\t{}", v)?;
5456
}
5557
Ok(())
5658
}
5759
}
5860

5961
fn main() {
60-
let vec: Vec::<u8> = vec![0, 0, 0, 0, 0];
62+
let vec: CustomVec<u8> = CustomVec(vec![0, 0, 0, 0, 0]);
6163
println!("Vec: {}", vec);
6264
}
6365
```
6466

65-
The basic idea is that we leverage the `write!` macro which takes the `Formatter` instance and writes some information to it. If any step fails, an error will be returned (we'll talk more about error handling and the `?` operator in chapter 19). If we iterate through the vector and are able to write all values successfully we can simply return the `Ok(())` result, which matches the the expected result type `fmt::Result`.
67+
The basic idea is that we leverage the `write!` macro which takes the `Formatter` instance and writes some information to it. If any step fails, an error will be returned (we'll talk more about error handling and the `?` operator in chapter 19). If we iterate through the vector and are able to write all values successfully we can simply return the `Ok(())` result, which matches the the expected result type `fmt::Result`. We need to create a `CustomVec<T>` using the [Newtype Pattern](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-the-newtype-pattern-to-implement-external-traits-on-external-types) to implement external traits on external types.
6668

6769
This might still be a bit confusing at this stage, so consider coming back to revisit this solution after you've gone through the course.

0 commit comments

Comments
 (0)