To summarize, I post a simple C++ example that illustrates my question. I want to write the equivalent in Rust. I have read the documentation, but I cannot find the precise answer to this.
#include <iostream>
using namespace std;
int _i;
void firstFunction() {
_i++;
}
void secondFunction() {
_i++;
}
int main()
{
firstFunction();
secondFunction();
cout << "Value of _i is: " << _i; // 2 (yes!)
}
My attempt at Rust
let mut _i:i32 = 0; // ?
fn firstFunction() {
_i = _i + 1;
}
fn secondFunction() {
_i = _i + 1;
}
fn main() {
firstFunction();
secondFunction();
println!("Value of _i is {}", _i); // must be 2
}
Answering my question, after the knowledge acquired by your excellent answers, I have written this approach, which seems closer to what I wanted to find,
struct Something {
counter: i32,
}
impl Something {
fn first_function(&mut self) {
self.counter = self.counter + 1;
}
fn second_function(&mut self) {
self.counter = self.counter + 1;
}
}
fn main() {
println!("Learning");
let mut _t = Something { counter: 0 };
_t.first_function();
_t.second_function();
println!("t: {}", _t.counter);
}