Update generics2.rs

This commit is contained in:
GURUSUJAN REDDY 2024-12-28 00:35:35 +05:30 committed by GitHub
parent 26cf4989a2
commit e4c85bc4fe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,18 +1,22 @@
// generics2.rs
//
// This powerful wrapper provides the ability to store a positive integer value. // This powerful wrapper provides the ability to store a positive integer value.
// TODO: Rewrite it using a generic so that it supports wrapping ANY type. // Rewrite it using generics so that it supports wrapping ANY type.
struct Wrapper { //
value: u32,
struct Wrapper<T> {
value: T
} }
// TODO: Adapt the struct's implementation to be generic over the wrapped value. impl <T> Wrapper<T> {
impl Wrapper { pub fn new(value: T) -> Self {
fn new(value: u32) -> Self {
Wrapper { value } Wrapper { value }
} }
} }
fn main() { fn main() {
// You can optionally experiment here. // This empty main function is needed, because the compiler expects it,
// while rustlings don't use this function for execution.
} }
#[cfg(test)] #[cfg(test)]
@ -21,11 +25,17 @@ mod tests {
#[test] #[test]
fn store_u32_in_wrapper() { fn store_u32_in_wrapper() {
assert_eq!(Wrapper::new(42).value, 42); assert_eq!(Wrapper::new(42u32).value, 42u32);
} }
#[test] #[test]
fn store_str_in_wrapper() { fn store_string_in_wrapper() {
assert_eq!(Wrapper::new("Foo").value, "Foo"); let x = Wrapper::new(String::from("Foo"));
assert_eq!(x.value, String::from("Foo"));
}
#[test]
fn store_f64_in_wrapper() {
assert_eq!(Wrapper::new(42.0_f64).value, 42.0_f64);
} }
} }