SlideShare a Scribd company logo
1 of 22
Download to read offline
Learn More
Lifetime in
Rust
Ayush Prashar
Software Consultant
Session
Etiquettes
● Respect session timings, you are requested not to join sessions
after a 5 minutes threshold post the session start time.
● Make sure to submit a constructive feedback for all sessions as
it is very helpful for the presenter.
● Keep your mobile devices in silent mode, feel free to move out
of session in case you need to attend an urgent call.
● Avoid unwanted chit chat during the session.
Agenda
1. Ownership
2. References
3. Dangling Reference
4. Borrow Checker
5. Lifetime Annotation
6. Lifetimes in Struct
7. Lifetime Ellison
8. Static Lifetime
Ownership
1. Each value in Rust has a variable known as its Owner.
2. There can be only one owner at a time.
3. When the owner goes out of scope, the value will be
dropped.
References
● References allow usage of variables without transfer
of ownership.
● It is denoted by & modifier.
Dangling
Reference
● References which point to illegal memory.
● Is the root of memory related bugs.
● Caught at compile time.
How does the
compiler know?
● Rust compiler has a borrow checker
● Borrow checker compares the scope of the reference
variable and the variable it is referencing.
● It ensures that the subject of reference variable lives
at least as long as the reference variable.
What if we can’t tell if a reference is valid?
We need to ensure that what the function may
return is valid.
Lifetime
Annotation
● A notation which describes relative lifetimes of
references.
● It never changes the lifetime of the references, just
constraints a specific lifetime.
● It tells that the references are valid for at least that
amount of time.
Lifetime
Annotation
● Syntax starts with an ‘ followed by a small case name
which is generally a single letter.
● fn<’a> foo(param1: &’a type) -> &’a return_value
● fn<’a> foo(param1: &’a mut type)->&’a return_value
How do we
calculate ‘a ?
● ‘a refers to the lifetime in which all the related
references are valid, which is the overlap all of the
references’ lifetimes.
● As a result, the smallest lifetime of all the references
gets assigned to ‘a.
Lifetime in Structs
● Struct fields could be a reference variable.
● In structs, they imply that the instance of a structure
can not out live the subject of reference of the field.
Lifetime Ellison
● Some coding patterns were very common and hence
annotating them was considered an overhead.
● Rust identified a few of them and designed some
rules.
● These rules are tested for at compile time and are
used to determine the lifetimes.
Lifetime Ellison
Rules
● Each input parameter gets its own lifetime
parameter.
● If there’s only one input parameter, its lifetime is
assigned to the returned value.
● If there are multiple input parameters but one of
them is &self or & mut self, it’s lifetime is assigned to
the returning value.
Lifetime Ellison
● If the compiler parses this code without any
annotation and there is no reference who’s lifetime is
not determined, the code is compiled successfully
● If the compiler can’t infer the lifetime of any
reference, it throws an error.
● These aren’t to follow, but available at the disposal of
the developer.
Static Lifetime
● Denotes lifetime of entire duration of the program.
● Denoted by ‘static.
● Means the reference can outlive anything.
● Anything static is directly provided inside the binary
of the program.
Static Lifetime
Variables with static lifetimes can be declared by two ways:
1. By declaring static constants
static AGE: i32 = 25;
2. By declaring string literals
let name: &’static str = “ayush prashar”;
References
1. The Rust Book(https://doc.rust-lang.org/book/index.html)
2. Stack Overflow
3. Reddit
4. Gitter Rust
Thank You!

More Related Content

What's hot

Countering Innovative Sandbox Evasion Techniques Used by Malware
Countering Innovative Sandbox Evasion Techniques Used by MalwareCountering Innovative Sandbox Evasion Techniques Used by Malware
Countering Innovative Sandbox Evasion Techniques Used by Malware
Tyler Borosavage
 

What's hot (20)

How to Monitoring the SRE Golden Signals (E-Book)
How to Monitoring the SRE Golden Signals (E-Book)How to Monitoring the SRE Golden Signals (E-Book)
How to Monitoring the SRE Golden Signals (E-Book)
 
SGX Trusted Execution Environment
SGX Trusted Execution EnvironmentSGX Trusted Execution Environment
SGX Trusted Execution Environment
 
DevOps Days Kyiv 2019 -- Victoria Metrics // Artem Navoiev
DevOps Days Kyiv 2019 -- Victoria Metrics // Artem NavoievDevOps Days Kyiv 2019 -- Victoria Metrics // Artem Navoiev
DevOps Days Kyiv 2019 -- Victoria Metrics // Artem Navoiev
 
The Log of All Logs: Raft-based Consensus Inside Kafka | Guozhang Wang, Confl...
The Log of All Logs: Raft-based Consensus Inside Kafka | Guozhang Wang, Confl...The Log of All Logs: Raft-based Consensus Inside Kafka | Guozhang Wang, Confl...
The Log of All Logs: Raft-based Consensus Inside Kafka | Guozhang Wang, Confl...
 
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
 
Secure Coding in C/C++
Secure Coding in C/C++Secure Coding in C/C++
Secure Coding in C/C++
 
Rate Limiting with NGINX and NGINX Plus
Rate Limiting with NGINX and NGINX PlusRate Limiting with NGINX and NGINX Plus
Rate Limiting with NGINX and NGINX Plus
 
Introducing Vault
Introducing VaultIntroducing Vault
Introducing Vault
 
How to upgrade like a boss to my sql 8.0?
How to upgrade like a boss to my sql 8.0?How to upgrade like a boss to my sql 8.0?
How to upgrade like a boss to my sql 8.0?
 
Using Optimizer Hints to Improve MySQL Query Performance
Using Optimizer Hints to Improve MySQL Query PerformanceUsing Optimizer Hints to Improve MySQL Query Performance
Using Optimizer Hints to Improve MySQL Query Performance
 
50 Shades of Sigma
50 Shades of Sigma50 Shades of Sigma
50 Shades of Sigma
 
PythonOOP
PythonOOPPythonOOP
PythonOOP
 
Derbycon - The Unintended Risks of Trusting Active Directory
Derbycon - The Unintended Risks of Trusting Active DirectoryDerbycon - The Unintended Risks of Trusting Active Directory
Derbycon - The Unintended Risks of Trusting Active Directory
 
Linux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old SecretsLinux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old Secrets
 
OSMC 2022 | Ignite: Observability with Grafana & Prometheus for Kafka on Kube...
OSMC 2022 | Ignite: Observability with Grafana & Prometheus for Kafka on Kube...OSMC 2022 | Ignite: Observability with Grafana & Prometheus for Kafka on Kube...
OSMC 2022 | Ignite: Observability with Grafana & Prometheus for Kafka on Kube...
 
Evading Microsoft ATA for Active Directory Domination
Evading Microsoft ATA for Active Directory DominationEvading Microsoft ATA for Active Directory Domination
Evading Microsoft ATA for Active Directory Domination
 
Countering Innovative Sandbox Evasion Techniques Used by Malware
Countering Innovative Sandbox Evasion Techniques Used by MalwareCountering Innovative Sandbox Evasion Techniques Used by Malware
Countering Innovative Sandbox Evasion Techniques Used by Malware
 
Vault
VaultVault
Vault
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language
 
Top 10 python ide
Top 10 python ideTop 10 python ide
Top 10 python ide
 

Similar to Lifetime in Rust

classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptx
ssusere336f4
 
Cucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptxCucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptx
Kalhan Liyanage
 

Similar to Lifetime in Rust (20)

Lifetime In Rust
Lifetime In RustLifetime In Rust
Lifetime In Rust
 
data types.pdf
data types.pdfdata types.pdf
data types.pdf
 
Lecture 2 keyword of C Programming Language
Lecture 2 keyword of C Programming LanguageLecture 2 keyword of C Programming Language
Lecture 2 keyword of C Programming Language
 
Lesson11 more behavioural patterns
Lesson11 more behavioural patternsLesson11 more behavioural patterns
Lesson11 more behavioural patterns
 
Programming in python - Week 2
Programming in python - Week 2Programming in python - Week 2
Programming in python - Week 2
 
basics dart.pdf
basics dart.pdfbasics dart.pdf
basics dart.pdf
 
Web development basics (Part-4)
Web development basics (Part-4)Web development basics (Part-4)
Web development basics (Part-4)
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptx
 
Class_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfClass_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdf
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Variables
VariablesVariables
Variables
 
C question-answer-bank
C question-answer-bankC question-answer-bank
C question-answer-bank
 
Elixir Brasil 2019 - Quality: A Panacéia para seu código Elixir
Elixir Brasil 2019 - Quality:  A Panacéia para seu código ElixirElixir Brasil 2019 - Quality:  A Panacéia para seu código Elixir
Elixir Brasil 2019 - Quality: A Panacéia para seu código Elixir
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 
CPP03 - Repetition
CPP03 - RepetitionCPP03 - Repetition
CPP03 - Repetition
 
Cucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptxCucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptx
 
Type checking compiler construction Chapter #6
Type checking compiler construction Chapter #6Type checking compiler construction Chapter #6
Type checking compiler construction Chapter #6
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 

More from Knoldus Inc.

More from Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Recently uploaded (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Lifetime in Rust

  • 1. Learn More Lifetime in Rust Ayush Prashar Software Consultant
  • 2. Session Etiquettes ● Respect session timings, you are requested not to join sessions after a 5 minutes threshold post the session start time. ● Make sure to submit a constructive feedback for all sessions as it is very helpful for the presenter. ● Keep your mobile devices in silent mode, feel free to move out of session in case you need to attend an urgent call. ● Avoid unwanted chit chat during the session.
  • 3. Agenda 1. Ownership 2. References 3. Dangling Reference 4. Borrow Checker 5. Lifetime Annotation 6. Lifetimes in Struct 7. Lifetime Ellison 8. Static Lifetime
  • 4. Ownership 1. Each value in Rust has a variable known as its Owner. 2. There can be only one owner at a time. 3. When the owner goes out of scope, the value will be dropped.
  • 5. References ● References allow usage of variables without transfer of ownership. ● It is denoted by & modifier.
  • 6.
  • 7. Dangling Reference ● References which point to illegal memory. ● Is the root of memory related bugs. ● Caught at compile time.
  • 8. How does the compiler know? ● Rust compiler has a borrow checker ● Borrow checker compares the scope of the reference variable and the variable it is referencing. ● It ensures that the subject of reference variable lives at least as long as the reference variable.
  • 9.
  • 10. What if we can’t tell if a reference is valid?
  • 11. We need to ensure that what the function may return is valid.
  • 12. Lifetime Annotation ● A notation which describes relative lifetimes of references. ● It never changes the lifetime of the references, just constraints a specific lifetime. ● It tells that the references are valid for at least that amount of time.
  • 13. Lifetime Annotation ● Syntax starts with an ‘ followed by a small case name which is generally a single letter. ● fn<’a> foo(param1: &’a type) -> &’a return_value ● fn<’a> foo(param1: &’a mut type)->&’a return_value
  • 14. How do we calculate ‘a ? ● ‘a refers to the lifetime in which all the related references are valid, which is the overlap all of the references’ lifetimes. ● As a result, the smallest lifetime of all the references gets assigned to ‘a.
  • 15. Lifetime in Structs ● Struct fields could be a reference variable. ● In structs, they imply that the instance of a structure can not out live the subject of reference of the field.
  • 16. Lifetime Ellison ● Some coding patterns were very common and hence annotating them was considered an overhead. ● Rust identified a few of them and designed some rules. ● These rules are tested for at compile time and are used to determine the lifetimes.
  • 17. Lifetime Ellison Rules ● Each input parameter gets its own lifetime parameter. ● If there’s only one input parameter, its lifetime is assigned to the returned value. ● If there are multiple input parameters but one of them is &self or & mut self, it’s lifetime is assigned to the returning value.
  • 18. Lifetime Ellison ● If the compiler parses this code without any annotation and there is no reference who’s lifetime is not determined, the code is compiled successfully ● If the compiler can’t infer the lifetime of any reference, it throws an error. ● These aren’t to follow, but available at the disposal of the developer.
  • 19. Static Lifetime ● Denotes lifetime of entire duration of the program. ● Denoted by ‘static. ● Means the reference can outlive anything. ● Anything static is directly provided inside the binary of the program.
  • 20. Static Lifetime Variables with static lifetimes can be declared by two ways: 1. By declaring static constants static AGE: i32 = 25; 2. By declaring string literals let name: &’static str = “ayush prashar”;
  • 21. References 1. The Rust Book(https://doc.rust-lang.org/book/index.html) 2. Stack Overflow 3. Reddit 4. Gitter Rust