Generics in Rust allow you to write code that works with different types without duplicating code for each specific type. They are commonly used in functions, structs, enums, and methods to make your code more reusable and flexible.
For this challenge, you will implement a generic struct ItemContainer that can store any type of item and provide methods to retrieve and manipulate the item.
Your Task
- Define a generic struct
ItemContainer<T>with a single fielditem: T. - Implement a method
get_itemthat returns a reference to the item.
Hints
If you're stuck, here are some hints to help you solve the challenge:
<details> <summary>Click here to reveal hints</summary>-
Define the struct as
ItemContainer<T>. e.g.struct ItemContainer<T> {item: T,}
← PreviousNext →
pub struct ItemContainer<T> {pub item: T,}impl<T> ItemContainer<T> {// TODO: Implement the `get_item` method to return a reference to the item.}// Example usagepub fn main() {let item_1 = ItemContainer { item: 42 };assert_eq!(*item_1.get_item(), 42);let item_2 = ItemContainer {item: String::from("Hello"),};assert_eq!(item_2.get_item(), "Hello");}