Skip to content

Latest commit

 

History

History
48 lines (35 loc) · 1.21 KB

3.md

File metadata and controls

48 lines (35 loc) · 1.21 KB

Structs, Lifetimes, Enums, Patterns

Structs

there are 3 types of structs in rust:

  • name field structs: gites a name to each component
  • tuple like structs: identifies them in the order which they appear
  • unit like structs: does not have components.
// field name
struct FieldName {
    name: String,
    another_name: String,
    last_name: String
}

// tuple structs
struct Cordinates(i32, i32);

// unit struct
struct UnitStruct;

Lifetimes

the main idea behind lifetimes is to prevent dangling references. lifetime annotations does not change how long a reference lives, it only describes the relationships of the lifetimes of multiple references to each other.

the rust compiler uses three rules to infer lifetimes when there are explicit annotations

  • each param that is a reference gets it's own lifetime parameter
  • if there is exactly one input lifetime param, it is assigned to all output lifetime parameters
  • if there are multiple lifetime input params and one of them is ref to a self, the lifetime of self is assigned to all output lifetime parameters
fn lifetime_eg<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {
    x
}

in structs:

struct MyString<'a> {
    text: &'a str,
}