-
Notifications
You must be signed in to change notification settings - Fork 10.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
18 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,36 @@ | ||
// generics2.rs | ||
// | ||
// 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. | ||
struct Wrapper { | ||
value: u32, | ||
// Rewrite it using generics so that it supports wrapping ANY type. | ||
// | ||
|
||
struct Wrapper<T> { | ||
value: T | ||
} | ||
|
||
// TODO: Adapt the struct's implementation to be generic over the wrapped value. | ||
impl Wrapper { | ||
fn new(value: u32) -> Self { | ||
impl <T> Wrapper<T> { | ||
pub fn new(value: T) -> Self { | ||
Wrapper { value } | ||
} | ||
} | ||
|
||
fn main() { | ||
// You can optionally experiment here. | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn store_u32_in_wrapper() { | ||
assert_eq!(Wrapper::new(42).value, 42); | ||
assert_eq!(Wrapper::new(42u32).value, 42u32); | ||
} | ||
|
||
#[test] | ||
fn store_string_in_wrapper() { | ||
let x = Wrapper::new(String::from("Foo")); | ||
assert_eq!(x.value, String::from("Foo")); | ||
} | ||
|
||
#[test] | ||
fn store_str_in_wrapper() { | ||
assert_eq!(Wrapper::new("Foo").value, "Foo"); | ||
fn store_f64_in_wrapper() { | ||
assert_eq!(Wrapper::new(42.0_f64).value, 42.0_f64); | ||
} | ||
} |