Created
September 26, 2021 18:09
-
-
Save xpepermint/f5cadd7bd75fbc475d8b5cfd614f06b5 to your computer and use it in GitHub Desktop.
Check if struct implements a specific trait
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
```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
Wow