简体   繁体   English

结构中的字符串,生命周期

[英]String in a struct, lifetime

I know what the difference between these 3 struct is - a lifetime of a 我知道这3个结构之间的区别是什么-一生a

struct S1 {
    a: &'static str,
    b: int
}

struct S2<'aa> {
    a: &'aa str,
    b: int
}

struct S3 {
    a: String,
    b: int
}

fn main() {
    let s1 = S1 {a: "123", b: 123};
    let s2 = S2 {a: "123", b: 123};
    let s3 = S2 {a: "123".into_owned(), b: 123};
}

Could you show me a use case of the 1st, 2nd and 3rd, in other words, when is it better to use the 1st over 2nd and 3rd, when - 2nd over 1st and 3rd, etc? 你能告诉我一个第一,第二和第三的用例,换句话说,什么时候使用第一个超过第二个和第三个,何时 - 第二个超过第一个和第三个等等? In the documentation there's no explanation. 在文档中没有解释。

S1 : This only allows you to use string literals, or other strings with a static (ie they can never be deallocated) lifetime. S1 :这只允许你使用字符串文字,或其他字符串与static (即它们永远不能解除分配)的生命周期。

S2 : This lets you use arbitrary string slices, provided they have an expressible lifetime. S2 :这允许您使用任意字符串切片,前提是它们具有可表达的生命周期。 For example, you cannot return dynamic instances of S2 from an Iterator , because there's no way to express the lifetime involved. 例如,您无法从Iterator返回S2动态实例,因为无法表达所涉及的生命周期。 That said, this allows you to avoid unnecessary heap allocations. 也就是说,这可以避免不必要的堆分配。

S3 : The most general, since it owns its contents, but requires heap allocation to use. S3 :最通用的,因为它拥有其内容,但需要使用堆分配。

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

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