Reputation: 246
I am learning rust so some things might seem obvious and easy but I can't understand some things.
I need to have income
and expenses
variables to change their value, usually I would use a static
variable and assign value in an unsafe
block.
Here is the code:
fn expense_sum(expense_list: &Vec<u64>, expenses: &mut u64) {
expenses = &mut (expense_list.iter().sum());
}
fn prompt_expense(expense_list: &mut Vec<u64>, expense_name: &mut Vec<String>, expenses: &mut u64) {
let expense_input: u64 = 1;
expense_list.push(expense_input);
let expense_name1: String = "test1".to_string();
expense_name.push(expense_name1);
expense_sum(&expense_list, expenses);
println!("Total user expenses: {}", expenses);
}
fn main() {
let mut expense_list: Vec<u64> = Vec::new();
let mut expense_name: Vec<String> = Vec::new();
let mut expenses: u64;
loop {
prompt_expense(&mut expense_list, &mut expense_name, &mut expenses);
// USe income and expenses here for analysis
}
}
I've tested in many ways, but I could not get to pass succesfully the variables to expense_sum
and income_sum
Upvotes: 0
Views: 95
Reputation: 39390
This is mostly correct; they only real issue preventing it from building is here:
fn expense_sum(expense_list: &Vec<u64>, expenses: &mut u64) {
expenses = &mut (expense_list.iter().sum());
}
This syntax tries to assign the reference, instead of modifying the actual value referred. You need to dereference and then simply assign:
*expenses = expense_list.iter().sum();
That being said, this is bad practice. It's much better to simply return the value using... the return value of the function:
fn expense_sum(expense_list: &Vec<u64>) -> u64 {
expense_list.iter().sum()
}
That way the code is shorter and much readable, and you avoid all the unnecessary reference handling. You'll need to modify your prompt_expense
function in a similar manner.
Upvotes: 2