可以将 'static 放在结构声明中吗?
Can 'static be placed along the struct declaration?
在Rust编程语言中,是否存在将'static
放在这里的情况:
struct Abc <'static> {
...
没有
如果没有指定泛型生命周期,每个类型都有一个隐式的 'static
生命周期。结构声明中的生命周期
struct Abc<'here, 'and, 'there>;
旨在指定结构包含较短的生命周期并为它们命名。 'static
作为一个特殊的生命不需要在这里指定或有一个本地名称。
但这并不意味着对于结构的特定实例,这些生命周期不能 'static
。
这有点像询问是否可以在结构声明中将 i32
指定为类型参数:
struct Abc<i32> {}
没有意义[1].
类型参数使结构的字段成为通用的:
struct Abc<T> {
foo: T, // a user of this struct can choose the type of T
}
同理,生命周期参数允许引用的生命周期是通用的:
struct Abc<'a> {
foo: &'a str, // a user of this struct can choose the lifetime bound
}
如果您希望生命周期始终是静态的,那么只需指定它,而不是使其通用:
struct Abc {
foo: &'static str, // this must always be static
}
[1] 实际上它声明了一个类型参数,它恰好与 i32
类型同名——但这不太可能是一个试图写东西的人本来就是这样的。
在Rust编程语言中,是否存在将'static
放在这里的情况:
struct Abc <'static> {
...
没有
如果没有指定泛型生命周期,每个类型都有一个隐式的 'static
生命周期。结构声明中的生命周期
struct Abc<'here, 'and, 'there>;
旨在指定结构包含较短的生命周期并为它们命名。 'static
作为一个特殊的生命不需要在这里指定或有一个本地名称。
但这并不意味着对于结构的特定实例,这些生命周期不能 'static
。
这有点像询问是否可以在结构声明中将 i32
指定为类型参数:
struct Abc<i32> {}
没有意义[1].
类型参数使结构的字段成为通用的:
struct Abc<T> {
foo: T, // a user of this struct can choose the type of T
}
同理,生命周期参数允许引用的生命周期是通用的:
struct Abc<'a> {
foo: &'a str, // a user of this struct can choose the lifetime bound
}
如果您希望生命周期始终是静态的,那么只需指定它,而不是使其通用:
struct Abc {
foo: &'static str, // this must always be static
}
[1] 实际上它声明了一个类型参数,它恰好与 i32
类型同名——但这不太可能是一个试图写东西的人本来就是这样的。