Converting `Population` from a Rust type to a trait! Episode 55 of Unhindered by Coding

preview_player
Показать описание

In moving towards making `Population` a trait, we made the `individuals` field private in the `Population` struct, thus hiding the `Vec` of `Individual` implementation detail from everyone and forcing us to better understand what things a `Population` needs to be able to do. Fixing the resulting compilation errors was mostly pretty straightforward (lots of uses of the existing and underused `is_empty` and `size` methods). The most complicated bit was implementing `FromIterator` and `FromParallelIterator` and adding an `iter` method to `Population`.

In the same vein, we also renamed the `Population` struct to `VecPop` so that the name `Population` would be free for our new trait.

So far the new trait only has two methods, `is_empty()` and `size()`. We have a nifty default implementation of `is_empty()` that uses `size()`, so we only have to implement `size()` in types that impl this trait.

The biggest win in this trait is arguably the associated type `Individual`. That manages to hide all references to the old `G` and `R` generics throughout, e.g., the selectors, and once we do something similar for `ChildMaker` we should be able to get rid of `G` and `R` from `Generation` as well!

I suspect that most, if not all, implementations of `Population` will also need to implement `IntoIterator`, so we might want to somehow cook that into this trait?

We removed `best_individual` from both `Population` and `Generation` since we have a `Selector` that does that, so we'll just keep that logic in that selector.

The biggest change was then to the selectors, which now are generic in `P: Population` instead of `G` and `R`. This led to a _lot_ of changes through the code.

There's a `where` clause in *every* selector's `select` method that is a quite annoying repetition. Can't we somehow say that once and have everyone get the memo?

I think this is a huge win, though, as the dependencies are clearer, and the generics are definitely moving in the right direction.

================

* Saturday afternoons from 2-4pm CDT, working on some possible lab exercises in Rust for our Systems Practicum course.

Thanks for watching!
Рекомендации по теме