Description
Currently, different instances of a generic function have an identical static variable.
For example, the following code
fn foo<T>() {
use std::sync::{Once, ONCE_INIT};
static INIT: Once = ONCE_INIT;
INIT.call_once(|| {
// run initialization here
println!("Called");
});
}
fn main() {
foo::<i64>();
foo::<i64>();
foo::<isize>();
}
calls println!
just once. This is because the entities of the static variable INIT
are the same for each different instance of the generic function foo
.
(Well, actually I have asked this in stackoverflow, but I only got a workaround to use HashMap essentially. Using dynamical way to dispatch static code sounds a bit uncomfortable. )
I feel this behavior of generic functions and static variables is counter-intuitive since each instances of generic functions have different name in assembly and thus they are different function.
Of course, I agree that changing it loses compatibility and may not be good, so I would like to ask whether there is any room to add a new syntax or something to allow for different instances of a generic function to have different static variables. I feel this is important especially when we "translate" some C++ template code into Rust.