Skip to content

Instantly share code, notes, and snippets.

@skull-squadron
Created May 19, 2025 20:31
Show Gist options
  • Save skull-squadron/1d6bc2521814fdb4b7eba6a33fc6a3c4 to your computer and use it in GitHub Desktop.
Save skull-squadron/1d6bc2521814fdb4b7eba6a33fc6a3c4 to your computer and use it in GitHub Desktop.
Rust anything (as opposed to just `Any`) type's to string
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