Generics, Traits, Lifetimes

Monomorphisation

Compiler uses above technique to compile the generic code and it internally replaces the generic types to concrete type.

Using this technique the performance would be same as any concrete type functions or struct or what not.

Traits

Traits are same like interfaces when compared to other programming languages

Now how to read the below function definition ?

fn some_function<T, U>(t: &T, u: &U) -> i32
    where T: Display + Clone,
          U: Clone + Debug
{
 .....
}

It could be read as follows - some_function accepts two parameters t & u where t parameter accepts the argument instance which implement both Display and Clone traits and u parameter accepts the argument instance which implements both Clone and Debug trait

I know the above is a mouthful to say but read it twice or thrice to understand it properly :)

Lifetimes Rules

  1. Each parameter which is a parameter gets it's own lifetime in a function

  2. The return result will get the same lifetime as parameter of a function if there is exactly one input reference parameter

  3. If the function has self that means if it's a method, then returning result reference parameters get the same lifetime as self

Last updated

Was this helpful?