0

My goal is to define a struct Wallet that has three fields:

  • A vector of denominations (e.g. [1, 5, 10, 20, 100]),
  • A vector number_of_bills indicating the number of each denomination present in the wallet (e.g. [0, 1, 2, 0, 1]),
  • And a vector value indicating the amount of money associated with each bill, i.e. the entrywise product [0, 5, 20, 0, 100] of denominations and vectors.

I would like to create a constructor that I can call like Wallet::new(&denominations, &number_of_bills) to automatically compute the value vector and obtain a complete instance of Wallet.

fn main() {
    println!("Hello, world!");
}


struct Wallet<'a> {
    denominations: &'a [usize],
    number_of_bills: &'a [usize],
    value: &'a [usize]
}


impl<'a> Wallet<'a> {
    fn new(denominations: &'a [usize], number_of_bills: &'a [usize]) -> Self {
        let value: Vec<usize> = denominations
            .iter()
            .zip(number_of_bills.iter())
            .map(|(&d, &n)| d * n)
            .collect();

        return Wallet {                              // (*)
            denominations: &denominations,
            number_of_bills: &number_of_bills,
            value: &value
        };
    }
}

This code does not compile, because in the indicated line we

cannot return value referencing local variable `value`

How can I accomplish this task?

Max
  • 695
  • 5
  • 18
  • Did you mean for the `Wallet` to *own* the vectors? i.e. `Vec`? `&[usize]` is an unowned slice of an array – Silvio Mayolo Mar 15 '22 at 05:32
  • For the purposes of this question, I am wondering if there is a way to construct this `Wallet` using borrowed arrays. – Max Mar 15 '22 at 05:36
  • Hello, see this [issue](https://stackoverflow.com/questions/32682876/is-there-any-way-to-return-a-reference-to-a-variable-created-in-a-function) – Zeppi Mar 15 '22 at 06:07
  • `Wallet::value` is a reference to borrowed data that lives elsewhere. The obvious question, then, is "where does the data live?" You're trying to borrow it from a local of `Wallet::new()`, but that local stops existing when the function returns. So what entity in your program is going to own it, if not the `Wallet` itself? – cdhowie Mar 15 '22 at 06:34
  • Thank you. I think @Caesar's link answers my question. – Max Mar 15 '22 at 07:12

0 Answers0