1

I am learning rust but I keep getting this error and I don't know how to solve it after spending time trying to solve it.

    error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src/main.rs:72:13
   |
72 |             income_list.push( 1);
   |             ^^^^^^^^^^^ cannot borrow as mutable

I've used lazy_static in order to create a global varibale with type u64:

lazy_static! {
    static ref expense_list: Vec<i64> = Vec::new();
    static ref income_list: Vec<u64> = Vec::new();
}

And I am trying to push value in it using the push() function:

let mut income_input = String::new();
io::stdin().read_line(&mut income_input);
let mut income_input: u64 = match income_input.trim().parse() {
    Ok(num) => num,
    Err(_) => break,
};
income_list.push(1); // it was income_list.push(income_input)

I can't push any value in the vector as it will keep throwing me that error, as per my understanding a vector should be a kind of array without a fixed-size.

Where am I wrong ?

Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
strangethingspy
  • 246
  • 1
  • 2
  • 13
  • Global variables are nothing one should use. Why don't you use a local variable instead? – hellow Jul 16 '19 at 09:37
  • @hellow Do you think, it's better to declare local variables in the main function and then use it there ? – strangethingspy Jul 16 '19 at 09:40
  • 2
    Yes! (!!!!!!!!!!). Borrow them (mutably) to the functions who need them. Global variables suffer from a lot of things, e.g. safe access from multi threaded programs. – hellow Jul 16 '19 at 09:42
  • Oh ok, will do then, thanks! I've always used global variables so it makes sense to not use them. – strangethingspy Jul 16 '19 at 09:44

1 Answers1

3

Your global variables are not mutable.

If you want mutable access to those Vecs, you have to wrap them in something that allows that, like Mutex or RwLock.

But you should follow @hellow's advice and rethink whether you really need these to be global variables. Sounds like you're trying to put your program's state into globals, when there's really no need to do so.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157