当我在泛型函数中使用静态变量时,泛型函数的每个实例中的变量实体都是相同的。
例如,在这段代码中
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 游乐场检查了汇编代码,发现INIT
变量与类型无关T
实际上是虽然foo<T>
它们自己用不同的名称实例化。
泛型函数的不同实例是否可以具有不同的静态变量,以便println!
在上面的例子中被调用了两次?
不可以。Rust 不支持将静态数据绑定到通用参数。
我能想到的最接近的解决方法是使用类似typemap https://crates.io/crates/typemap用于存储每种类型一个条目的板条箱。
/*!
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");
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)