How to add a static/global variable in a single trait impl?

I am learning Rust OOP, I have this trait

pub struct Animal {
  fn speak() -> ();
}

I implement two animals below:

// cat.rs
pub struct Cat;

impl Animal for Cat {
  fn speak() -> () {
    println!("Meow!")
  }
}

// dog.rs
pub struct Dog;

impl Animal for Dog {
  fn speak() -> () {
    println!("Woof!")
  }
}

Now, if I want to add a variable to only the Cat impl, like this:

// cat.rs
pub struct Cat;

impl Animal for Cat {
  const name: &'static str = "Felix";

  fn speak() -> () {
    // do something with name
    println!("Meow!")
  }
}

I get the error:

error[E0438]: const `name` is not a member of trait `Animal`
 --> src/cat.rs:5:5
  |
6 |     const name: &'static str = "Felix";
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not a member of trait `Animal`

For more information about this error, try `rustc --explain E0438`.

Why can’t I add some variables scoped to a specific impl (class?)

>Solution :

Yes you have to do in two step

pub trait Animal {
  fn speak() -> ();
}

pub struct Cat;

impl Cat {
    const name: &'static str = "Felix";

    //.. fn new or other method
}

impl Animal for Cat {     
  fn speak() -> () {
    // do something with name
    println!("Meow!")
  }
}

Leave a Reply