简体   繁体   中英

I need help using mutable reference in different functions

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM