Skip to content

Instantly share code, notes, and snippets.

@cowboy-bebug
Created October 20, 2019 23:09
Show Gist options
  • Save cowboy-bebug/851f4d28f88a87d7ca4c71c47cfd4f99 to your computer and use it in GitHub Desktop.
Save cowboy-bebug/851f4d28f88a87d7ca4c71c47cfd4f99 to your computer and use it in GitHub Desktop.
Multiple impls of a trait on the same type
// Source: https://codesandwich.github.io/overlapping_blanket_impls/
use std::convert::TryInto;
// Dummy Trait
trait Blanket<I> {
fn blanket(&self) -> &'static str;
}
// Dummy Structs
struct Numbers;
struct Strings;
impl<T: TryInto<u8>> Blanket<&Numbers> for T {
fn blanket(&self) -> &'static str {
"try_into"
}
}
impl<T: AsRef<[u8]>> Blanket<&Strings> for T {
fn blanket(&self) -> &'static str {
"as_ref"
}
}
fn main() {
assert_eq!("try_into", Blanket::blanket(&1_i8));
assert_eq!("try_into", Blanket::blanket(&1_u8));
assert_eq!("as_ref", Blanket::blanket(&"str"));
assert_eq!("as_ref", Blanket::blanket(&"str".to_string()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment