我使用的是规范的ECS库,我有以下类型
trait TradeableResource{}
#[derive(Component)]
struct MarketMaker<T: TradeableResource + std::marker::Send + std::marker::Sync + 'static>{
lot_size:T
}
如果不使用 'static
的约束。我最初担心,这将意味着这个结构的所有值都必须在程序的整个生命周期内生存。不过 样子 左右,看来这种担心是无效的。那些链接明明涉及到了这个话题,但是我觉得他们没有用语言,导致我没有明确的心理模型。所以我想就这个话题发表一下自己的声明,你告诉我是否正确。
我的声明
通过使用 'static
约束,任何类型都可以填补这一类型的位置。T
必须 要么
所以,下面的特殊情况下,不需要任何东西在程序的整个生命周期内都能使用
#[derive(Component)]
struct Food(f64);
impl TradeableResource for Food{}
fn main() {
let mut world = World::new();
world.register::<MarketMaker<Food>>();
world.create_entity().with(MarketMaker { lot_size: Food(4.0)}).build();
}
因为该类型 Food
只包含拥有的值,没有引用。
我说的对吗?
TLDR:是的,你说的没错。
确实如此 'static
术语有点过载。它可以作为寿命规定符使用,如
const T: &'static str = "static string here";
fn handle_static<T>(t: &'static T) { .. }
和作为类型约束。
trait T: 'static { .. }
fn handle_owned<T>(t: T)
where T: 'static { .. }
这些都是相当不同的情况,你的例子和第二个例子类似。你的说法是正确的,下面的例子可以说明这一点(游乐场):
struct X<'a> {
borrowed_str: &'a str,
}
let base_str = "".to_string();
// X'es lifetime bounded by base_str
let borrows = X {
borrowed_str: base_str.as_str(),
};
let borrows_static = X { borrowed_str: "" };
fn f<T>(t: T) where T: 'static {}
// the following line fails to compile
// f(borrowed);
f(borrows_static); // though, with 'static lifetime works
f(base_str); // owned, also works fine
我还建议你看看令人惊异的 常见的锈蚀寿命误区 如果你想对这个或类似的误区有一个结构化的指导,就可以发帖。