Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String in a struct, lifetime

Tags:

rust

I know what the difference between these 3 struct is - a lifetime of 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.

like image 465
Incerteza Avatar asked Nov 25 '14 03:11

Incerteza


People also ask

What are lifetimes in Rust?

Lifetimes are what the Rust compiler uses to keep track of how long references are valid for. Checking references is one of the borrow checker's main responsibilities. Lifetimes help the borrow checker ensure that you never have invalid references.

How do you declare a string in Rust?

String Literal For example, let company="Tutorials Point". String literals are found in module std::str. String literals are also known as string slices. The following example declares two string literals − company and location.

WHAT IS A in Rust?

The 'a reads 'the lifetime a'. Technically, every reference has some lifetime associated with it, but the compiler lets you elide (i.e. omit, see "Lifetime Elision") them in common cases. fn bar<'a>(...) A function can have 'generic parameters' between the <> s, of which lifetimes are one kind.

What is a struct in Rust?

A struct is a user-defined data type that contains fields which define its particular instance. Structs help programmers implement abstract ideas in a more understandable fashion. For example, creating a Student struct that consists of an id , name , marks , etc. makes the code more readable.


1 Answers

S1: This only allows you to use string literals, or other strings with a static (i.e. they can never be deallocated) lifetime.

S2: This lets you use arbitrary string slices, provided they have an expressible lifetime. For example, you cannot return dynamic instances of S2 from an Iterator, because there's no way to express the lifetime involved. 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.

like image 56
DK. Avatar answered Sep 19 '22 12:09

DK.