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

Enum & From Trait | Rust Language

Поделиться
HTML-код
  • Опубликовано: 13 авг 2024
  • Learning to use the From trait with an Enum - using map to return an array of a different type.
    Try the code in Rust Playground:
    ----------------------------------------------------
    play.rust-lang.org/?version=s...
    #rustprogramming #learningrust #practiceRust

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

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

    You don't really need to implement the "from_array" method. I mean, you can, but it always seemed a bit redundant to me.
    There is a shorthand when using the map function on iterators if the operand signature matches the item type in the array:
    ```
    let vehicle_array: [u32; 4] = [1, 2, 3, 4];
    let vehicle_vec = vehicle_array.map(Vehicle::from);
    ```
    So it's kinda simple without the extra method.
    And if you really wanna be all "fancy" and add a variadic version of the function (a function that accept an arbitrary number or parameters), you can create a macro like this:
    ```
    #[macro_export]
    macro_rules! vehicle {
    ($($num:expr),*) => { [$(Vehicle::from($num)),*] };
    }
    ```
    Which allows you to call the function with any number of variables and get back an array like this:
    ```
    let vehicle_vec = vehicle!(1, 2, 3, 4);
    ```
    My approach is usually to implement as little functionality as possible to a struct. But that's just me, it's not necessarily a good or bad practice, I just like my API's as small and lean as possible.

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

      Thank you! - " implement as little functionality as possible to a struct" - I like that approach - I'm glad you commented, appreaciate it - it's invaluable to read stuff like this.
      I guess the from_array method might be more suitable if it was part of a custom trait (maybe)

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

    you lost me as soon as you opened NV,