Это видео недоступно.
Сожалеем об этом.

Trait Based Polymorphism | Rust Language

Поделиться
HTML-код
  • Опубликовано: 29 май 2024
  • Learning to use Traits with enums and multiple structs | Polymorphism.
    "This Rust code defines a trait Animal with a method make_sound(). Two structs, Cat and Dog, implement this trait. An enum Pet is defined to represent either a cat or a dog. The Animal trait is then implemented for the Pet enum, delegating the make_sound() method based on the variant.
    A function sounds() takes a string representing a pet type ("cat" or "dog") and returns a corresponding Pet. In the main() function, it creates a pet based on the input string and prints its sound."
    Links:
    🟩 tourofrust.com/index.html
    🟩 github.com/RGGH/return_trait
    🟩 webdock.io/en?maff=wdaff--170
    🟩 users.rust-lang.org/t/polymor...
    Code:
    🟩 github.com/RGGH/trait_impl_enums
    #Traits #rustprogramming #learningrust

Комментарии • 2

  • @phillduffy
    @phillduffy 2 месяца назад +1

    Great video again.
    What would the benefit of impl Animal for the structs rather than just using it on the enum?
    impl Animal for PetType { fn make_sound(&self) -> &str { match self { PetType::Catly => "miaow mieew", PetType::Dogly => "bow wow wow", } } }

    • @learning_rust
      @learning_rust  2 месяца назад

      Yes, so without the impl on the structs, I get this error : items from traits can only be used if the trait is implemented and in scope
      note: `Animal` defines an item `make_sound`, perhaps you need to implement it.
      I did try a few different approaches. I also used Box /Dynamic Dispatch with the function for pet_setup - but figured static dispatch is preferable in production?