Exerpad
🔥0
0 XP
Lv.1 Beginner
Log In

Generic Method

Create a generic struct Box<T> (call it MyBox to avoid conflict with Rust's built-in) with a field item: T. Add a method peek that borrows self and prints the item. Test it with MyBox { item: "treasure" }.

Expected output:

text
Inside the box: treasure

Hints:

  • struct MyBox<T> { item: T }
  • impl<T: std::fmt::Display> MyBox<T> { fn peek(&self) { ... } }
  • The trait bound T: std::fmt::Display lets you use {} to print
rust
fn main() {
}