Skip to content

Instantly share code, notes, and snippets.

@KennFatt
Created July 23, 2020 16:41
Show Gist options
  • Save KennFatt/9cc89a6669af9ccc6e9b5ab0753af7a1 to your computer and use it in GitHub Desktop.
Save KennFatt/9cc89a6669af9ccc6e9b5ab0753af7a1 to your computer and use it in GitHub Desktop.
Generic function that will return a type based on the annotations.
#[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