#Trait implementation implemented through proc macro not found

8 messages · Page 1 of 1 (latest)

placid garden
#

I am trying to learn about proc macros, but etting up the project is the hardest part rn 😓
I have created a rust package with --lib called hello_macro
and then created another rust packagae within that package called hello_macro_derive
I have included the hello_macro_derive as a dependency in the cargo.toml of hello_macro

But when in my hello_macro/src/main.rs
I have the following code with a compiler error

use hello_macro::Hello;

#[derive(Hello)]
struct Foo;

fn main() {
    let foo = Foo;
    println!("{}", foo.name());
    // error: no method named `name` found for struct `Foo` in the current scope method not found in `Foo`
}
lament epoch
#

Is that a trait method? Is the trait imported?

placid garden
# placid garden I am trying to learn about proc macros, but etting up the project is the hardest...

hello_macro/src/lib.rs looks like

pub use hello_macro_derive::Hello;

pub trait Hello {
    fn hello(&self) -> &'static str;
}

and hello_macro/hello_macro_derive/src/lib.rs
looks like

extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::{self, DeriveInput};

#[proc_macro_derive(Hello)]
pub fn hello_derive(input: TokenStream) -> TokenStream {
    let ast: DeriveInput = syn::parse(input).unwrap();

    let ident = &ast.ident;
    let ident_str = ident.to_string(); 
    quote! {
        impl Hello for #ident {
            fn hello(&self) -> &'static str {
                #ident_str
            }
        } 
    }.into()
}
placid garden
lament epoch
#

Hmm. What does cargo expand output? (you might need to cargo install cargo-expand, if you don't have it already)

placid garden
#

how do I use that command and where?

lament epoch
#

cargo expand Foo, I believe? Something of the sort, it should output the result of expanding macros on that struct

placid garden
#

ah I just realised my function is called .hello(),
I am calling .name()...