Generics
Generics is the topic of generalizing types and functionalities to broader cases. This is extremely useful for reducing code duplication in many ways, but can call for rather involving syntax. Namely, being generic requires taking great care to specify over which types a generic type is actually considered valid. The simplest and most common use of generics is for type parameters.
Further information
Rustlings
generics1
// This shopping list program isn't compiling! // Use your knowledge of generics to fix it. // Execute `rustlings hint generics1` or use the `hint` watch subcommand for a hint. // I AM NOT DONE fn main() { let mut shopping_list: Vec<?> = Vec::new(); shopping_list.push("milk"); }
rustlings-solutions-5/generics at main · gaveen/rustlings-solutions-5
Hint
Vectors in Rust make use of generics to create dynamically sized arrays of any type. You need to tell the compiler what type we are pushing onto this vector.
solution1: &str
// This shopping list program isn't compiling! // Use your knowledge of generics to fix it. // Execute `rustlings hint generics1` or use the `hint` watch subcommand for a hint. fn main() { let mut shopping_list: Vec<&str> = Vec::new(); shopping_list.push("milk"); }
solution2: String
// This shopping list program isn't compiling! // Use your knowledge of generics to fix it. // Execute `rustlings hint generics1` or use the `hint` watch subcommand for a hint. fn main() { let mut shopping_list: Vec<String> = Vec::new(); shopping_list.push("milk"); // fix here }
generics2
// This powerful wrapper provides the ability to store a positive integer value. // Rewrite it using generics so that it supports wrapping ANY type. // Execute `rustlings hint generics2` or use the `hint` watch subcommand for a hint. // I AM NOT DONE struct Wrapper { value: u32, } impl Wrapper { pub fn new(value: u32) -> Self { Wrapper { value } } } // #[cfg(test)] // mod tests { // use super::*; // // #[test] // fn store_u32_in_wrapper() { // assert_eq!(Wrapper::new(42).value, 42); // } // // #[test] // fn store_str_in_wrapper() { // assert_eq!(Wrapper::new("Foo").value, "Foo"); // } // } // change to run in playground fn main() { assert_eq!(Wrapper::new(42).value, 42); assert_eq!(Wrapper::new("Foo").value, "Foo"); }
Hint
Currently we are wrapping only values of type ‘u32’. Maybe we could update the explicit references to this data type somehow?
If you are still stuck, please read:
solution1: convert to use generics
// This powerful wrapper provides the ability to store a positive integer value. // Rewrite it using generics so that it supports wrapping ANY type. struct Wrapper { // fix here value: T, } impl<T> Wrapper<T> { pub fn new(value: T) -> Self { Wrapper { value } } } fn main() { assert_eq!(Wrapper::new(42).value, 42); assert_eq!(Wrapper::new("Foo").value, "Foo"); }