mercredi 18 novembre 2020

What the Rust approach to constructurs for types with references?

In a Rust project of mine, I have constructors that build convenient instances of some types.

Let's say I model a fridge with apples:

struct Apple {};

struct Fridge {
  apples: Vec<&apples>,

  fn ready_fridge() -> Fridge {
    Fridge { /* with 2 apples */ }
  }
}

I'd like the read_fridge() constructor to prepare a fridge with two apples; how can I do that?

It's not directly possible, because the apples are allocated on the stack, so they can't be returned.

I tried with lazy_static, however, it gets messy (and I couldn't make it work anyway).

Is there any way? Maybe, the design is wrong, instead?

Aucun commentaire:

Enregistrer un commentaire