Created
July 23, 2020 16:41
-
-
Save KennFatt/9cc89a6669af9ccc6e9b5ab0753af7a1 to your computer and use it in GitHub Desktop.
Generic function that will return a type based on the annotations.
This file contains hidden or 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
#[derive(Debug)] | |
struct MyError(String); | |
trait Poke { | |
fn aw(); | |
} | |
struct Lovely; | |
impl Poke for Lovely { | |
fn aw() { | |
println!("Awww lovely...!"); | |
} | |
} | |
impl std::default::Default for Lovely { | |
fn default() -> Self { | |
Self {} | |
} | |
} | |
struct Hurtly; | |
impl Poke for Hurtly { | |
fn aw() { | |
println!("Aww it hurts!"); | |
} | |
} | |
impl std::default::Default for Hurtly { | |
fn default() -> Self { | |
Self {} | |
} | |
} | |
fn main() -> Result<(), MyError> { | |
let _: Lovely = poke_something()?; | |
let _: Hurtly = poke_something()?; | |
Ok(()) | |
} | |
fn poke_something<T: Poke + Default>() -> Result<T, MyError> { | |
T::aw(); | |
Ok(T::default()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment