How to use the trait of a structure in this simple way?

Hi,

I have this simple code in which I want to call the is_valid and do_stuff functions.

Is there a way to specify this?
I thought we could clarify, but this is not the way envisaged without recording a macro ourselves and I would like to know how to do it without please?

#[derive(Validator)]
struct MyStruct {
   n : i32,
}

impl MyStruct {
   fn do_stuff(&self) {
       println!("{}", self.n);
   }
}

trait Validator {
    fn is_valid(&self) -> bool;
}

fn main() {

    let s = MyStruct { n : 4 };
    s.do_stuff();
    s.is_valid();
}

Are you asking how to implement Validate for MyStruct without a derive macro?

impl Validator for MyStruct {
    fn is_valid(&self) -> bool {
        self.n == 42 // or whatever it means for MyStruct to be valid
    }
}
1 Like

Sorry, I miss this part. Shame on me...

You either implement that trait or go the long way of procedural macros, you can read more in here:
https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros

Thank you.

In fact, I always try to make a little example when my code does not work to find the problem before asking help.
But, my error was that I forgot to use the trait in another file...
I learn some stuff about macro by the way... ^^