泛型函数的不同实例是否可能具有不同的静态变量? [英] Is it possible for different instances of a generic function to have different static variables?

查看:38
本文介绍了泛型函数的不同实例是否可能具有不同的静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在泛型函数中使用静态变量时,泛型函数的每个实例中变量的实体都是一样的.

When I use a static variable in generic functions, the entities of the variable in each instance of the generic function are all the same.

例如,在这段代码中

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>();
}

println! 只调用一次.

我使用 Rust playground 检查了汇编代码,发现 INIT 变量与 T 实际是哪种类型无关,尽管 foo 本身使用不同的名称进行实例化.

I had checked the assembly code using the Rust playground and saw that the INIT variable is independent of which type T actually is although foo<T> themselves are instantiated with different name.

泛型函数的不同实例是否有可能具有不同的静态变量,以便在上面的示例中调用 println! 两次?

Is it possible for different instance of the generic function to have different static variables so that println! is called twice in the above example?

推荐答案

没有.Rust 不支持将静态数据绑定到泛型参数.

No. Rust doesn't support having static data tied to a generic parameter.

我能想到的最接近的解决方法是使用类似 typemap crate 用于存储每种类型的一个条目.

The closest workaround I can think of would be to use something like the typemap crate to store one entry per type.

/*!
Add to `Cargo.toml`:

```cargo
[dependencies]
lazy_static = "0.2.8"
typemap = "0.3.3"
```
*/
#[macro_use] extern crate lazy_static;
extern crate typemap;

fn main() {
    foo::<i64>();
    foo::<i64>();
    foo::<isize>();
}

fn foo<T: 'static>() {
    use std::marker::PhantomData;
    use std::sync::Mutex;
    use typemap::{ShareMap, TypeMap};

    // Use `fn(T)` as it avoids having to require that `T` implement
    // `Send + Sync`.
    struct Key<T>(PhantomData<fn(T)>);

    impl<T: 'static> typemap::Key for Key<T> {
        type Value = ();
    }

    lazy_static! {
        static ref INIT: Mutex<ShareMap> = Mutex::new(TypeMap::custom());
    }

    INIT.lock().unwrap().entry::<Key<T>>().or_insert_with(|| {
        println!("Called");
    });
}

这篇关于泛型函数的不同实例是否可能具有不同的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆