简体   繁体   English

具有 static 寿命的类型意味着什么?

[英]What does it mean for a type to have a static lifetime?

I understand what it means for a borrow, trait, or struct to have a lifetime, but it doesn't make sense to me why a type would have one.我理解借用、特征或结构具有生命周期意味着什么,但对我来说为什么一个类型会有生命周期是没有意义的。 My understanding of types is that they are an abstraction that is used at compile time, and they don't need to exist at all in the binary.我对类型的理解是它们是在编译时使用的抽象,它们根本不需要存在于二进制文件中。 For example, a struct with a two ints, a tuple of two ints, and a fixed-size array of two ints should all map to the same arrangement of values in memory when compiled, and the code would use byte offsets to find those two values.例如,具有两个 int、一个由两个 int 组成的元组和一个由两个 int 组成的固定大小数组的结构在编译时应该全部 map 到 memory 中的相同值排列,并且代码将使用字节偏移量来找到这两个价值观。 If I am correct about that, the concept of a lifetime shouldn't apply to types at all, so the following two structs would be equivalent:如果我是正确的,生命周期的概念根本不应该适用于类型,所以以下两个结构是等价的:

pub struct Foo<T> {
    foo: T
}

pub struct Bar<T: 'static> {
    bar: T
}

Beyond just being equivalent, the syntax wouldn't exist at all.除了等效之外,语法根本不存在。 I must be misunderstanding something, and extensive googling has not helped.我一定是误解了一些东西,广泛的谷歌搜索并没有帮助。 What is the purpose of type lifetimes, and when are they supposed to be used?类型生命周期的目的是什么,应该在什么时候使用它们?

T can carry lifetimes shorter than 'static . T可以携带比'static更短的生命周期。 For instance, T could be some &'a str (for some 'a ), so Foo<T> becomes Foo<&'a str> and therefore has a bound to 'a , which may be shorter than 'static .例如, T可能是一些&'a str (对于一些'a ),所以Foo<T>变为Foo<&'a str>并因此绑定到'a ,它可能'static短。

The first definition accepts any T and will be bound in its lifetime to T .第一个定义接受任何T并将在生命周期内绑定到T The second definition says that T must not contain lifetimes shorter than 'static ( T could be &'static str , String or anything else that is 'static ).第二个定义说T不能包含比'static更短的生命周期( T可以是&'static strString或任何其他'static )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM