Skip to content

Instantly share code, notes, and snippets.

@xpepermint
Created September 26, 2021 18:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xpepermint/f5cadd7bd75fbc475d8b5cfd614f06b5 to your computer and use it in GitHub Desktop.
Save xpepermint/f5cadd7bd75fbc475d8b5cfd614f06b5 to your computer and use it in GitHub Desktop.
Check if struct implements a specific trait
```rs
// Based on: https://www.reddit.com/r/rust/comments/ehr8ct/announcing_impls_a_macro_to_determine_if_a_type/
// trait for T
trait TTrate {
const VALUE: bool = false;
}
impl<T> TTrate for T {}
// custom trait
trait MyTrait {}
impl MyTrait for Vec<u32> {}
// example structure
struct Example<T>(std::marker::PhantomData<T>);
impl<T: MyTrait> Example<T> {
const VALUE: bool = true;
}
// run
fn main() {
println!("Implements MyTrait?");
println!("=> {}", Example::<u32>::VALUE);
println!("=> {}", Example::<Vec<u32>>::VALUE);
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment