Created
May 19, 2025 20:31
-
-
Save skull-squadron/1d6bc2521814fdb4b7eba6a33fc6a3c4 to your computer and use it in GitHub Desktop.
Rust anything (as opposed to just `Any`) type's to string
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
pub trait TypeName { | |
fn type_name(&self) -> &str { | |
std::any::type_name::<Self>().trim_start_matches("dyn::") | |
} | |
} | |
impl<T> TypeName for T {} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn test_i32() { | |
assert_eq!(1_i32.type_name(), "i32"); | |
} | |
#[test] | |
fn test_option() { | |
assert_eq!(Some(5_i32).type_name(), "Option<i32>"); | |
} | |
#[test] | |
fn test_struct() { | |
struct Foo; | |
assert_eq!(Foo.type_name(), "Foo"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment