Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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!")
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading