Help me with this brain teaser

Hello everyone, I'm fooling around, trying to increase my knowledge of the language.

Today I'm trying to solve this problem.

I'd like to implement the Farmer trait below. I hereby list some facts that may or may not help:

  1. The Farmer trait must not be generic.
  2. The number of structs that implement the Stage trait is known, but Stage must at all cost be a trait.
  3. The Crops associated type of the Farmer trait will most likely be a struct containing one Vector for each life cycle of the plant. This struct contains only one type that implements FarmPlant.
  4. The farm method of the Farmer trait will most likely be used while looping through Crops.
struct Seed;
struct Young;
struct Mature;
struct Flower;
struct Fruit;

pub trait Stage {}

impl Stage for Seed {}
impl Stage for Young {}
impl Stage for Mature {}
impl Stage for Flower {}
impl Stage for Fruit {}

pub trait FarmPlant<D: Stage> {}

// This to me feels like a natural way of doing thigs, but
// I'd very much like to remain on stable.
pub trait Farmer { // A farmer can attend to only a type of crop.
     type Crops; // A struct containing a vector for each of the crop's life cycles.
     type Crop<D: Stage>: FarmPlant<D>;
     fn farm<D: Stage>(&self, crop: &Self::Crop<D>);
     fn crops(&self) -> &Self::Crops;

Assuming that when you farm, you update your self -- i.e. that you really want:

fn farm<D: Stage>(&mut self, crop: &Self::Crop<D>);

Then you're going to run into borrow errors trying to use this trait as described, as implementors will be trying to both borrow from themselves with crops and mutate themselves with farm simultaneously. (Interior mutability may be a possibility.)

That aside, exactly what you want still isn't clear to me, but I played with it some anyway.

1 Like