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]
ofdenominations
andvectors
.
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?