<ao> | Adetunji's Blog

impl, Giving super powers to enums and structs

The impl keyword gives us the ability to write function for both an enum and a struct. This functions are called methods

There are two different types of methods:

The major difference between both can be seen in code below

fn main(){
  let mut my_string = String::from('Ade'); //we couldn't my_string.some_method() until it's created using String::from()
  my_string.push('tunji') // my_string is created already and regular function can be called on it now.
}

Using Attribute one can give the ability to print out the variants in an Enum: Give enum and struct the ability to be formatted

Example

#[derive(Debug)]
enum AnimalType{
  Cat,
  Dog,
}

#[derive(Debug)]
struct Animal{
  age: u8,
  animal_type: AnimalType,
}

impl Animal{
  fn new_cat() -> Self{
    Self{
      age: 10,
      animal_type: AnimalType::Cat
      }
   }

  fn check_type(&self){
    match self.animal_type{
      AnimalType::Dog => println!("The animal is a dog"),
      AnimalType::Cat => println!("The animal is a cat"),
	}
  }
	
  fn change_to_dog(&mut self){
    self.animal_type = AnimalType::Dog;
    println!("Change animal to dog! now it's a {self:?}")
  }

  fn change_to_cat(&mut self){
    self.animal_type = AnimalType::Cat;
    println!("Change animal to cat! now it's a {self:?}")
  }
}

fn main(){
  let mut new_animal = Animal::new_cat();
  new_animal.check_type();
  new_animal.change_to_dog();
  new_animal.check_type();
  new_animal.change_to_dog();
  new_animal.check_type();
}

#note #rust