I wanted to get the same as static variables in C++ -- a variable shared between all instances of a struct and can be modified. However, the below code does not work...how is this done in rust?
struct Foo{
static a: usize,
}
// in main.rs I wanted to write something like Foo::a = 5.
EDIT: here's the specific use case I have in mind. I have a struct called Polynomial
and all instances should have a common degree which is an int. There are also a vector of constants v
which facilitates multiplying two polynomials together, and is parametrized by the degree. So overall I wish to have the two variables n: int
and v: Vec<i32>
visible to all the instances of the struct, but the precise value of n will be given by user and v will be computed from n at the beginning of program. So the files in my hope could looks like
struct Polynomial{
// common n: int,
// common v: Vec<i32>,
pub fn multiply(&self, Other:self) -> Self{
// make use of n and v.
}
}
and then specify the values at runtimes like
fn main(){
Polynomial::n = get_n_from_user();
Polynomial::v = compute_v_from_n(n);
}
so I wanted to see how to make the above work in Rust. Thanks!
EDIT2: So I realized that I don't actually need to "mutate" the variable. I just need it to be able to set at runtime. I was trying with const
keyword but that requires me to hard-code the value so that does not work.