Skip to content

Different static variables for different instances of a generic function #2130

Closed
@hajifkd

Description

@hajifkd

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions