Implementing a simple trait

Let's see how this can be done by implementing a simple trait for a structure or enumeration. The trait we will be implementing is the following:

trait TypeName {    fn type_name() -> &'static str;}

This trait should return the name of the current structure or enumeration as a string. Implementing that by hand is really easy, but it doesn't make sense to implement it manually, one by one, for our types. The best thing to do is to derive it with a procedural macro. Let's see how we can do that.

First, we will need to create a library crate. As per convention, it should have the parent crate's name and then the -derive suffix. In this case, we do not have a name for the crate, but let's call the library type-name-derive ...

Get Rust High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.