SlideShare a Scribd company logo
Rust
About Rust
● New systems programming language by Mozilla.
● Designed to write secure code:
● Memory safety
● Thread safety
● Performance similar to C++
Hello, world!
fn main() {
println!(“Hello, world!”);
}
$ rustc hello.rs
$ ./hello
Hello, world!
Cargo
Cargo.toml
[package]
name = "program"
version = "0.1.0"
authors = ["John D <john.d@test.com>"]
[features]
default = [ ]
[dependencies]
num = "0.1.27"
Commands
$ cargo build
$ cargo test
$ cargo run
$ cargo new title [--bin]
Tool used for downloading dependencies, building dependencies and
building our program.
Syntax
fn increase(x: i32) -> i32 {
x + 1
}
fn swap(tuple: (i32, i32)) -> (i32, i32)
{
let (x, y) = tuple;
(y, x)
}
fn main() {
println!("{}", increase(10));
let my_tuple = (10, 20);
println!("{:?}", swap(my_tuple));
}
$ rustc syntax.rs
$ ./syntax
11
(20, 10)
Variable bindings
A 'let' expression is a pattern:
let(x, y) = (42, 24); // x = 42, y = 24
Variable bindings are immutable by default:
let x = 42;
x = 10;// error
let mut x = 42;
Type inference:
let x: i32 = 10; // Same as let x = 10;
Stack and Heap
fn main() {
let x = Box::new(5);
let y = 42;
let z = &x;
}
Box<T> implements Drop, it is freed when it goes out of
scope
Address Name Value
2^30
...
5
2 z → 0
1 y 42
0 x → 2^30
Vector
● Provided by the std library
● Growable (dynamic)
● Can implement any type: Vec<T>
let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>
let mut my_vector: Vec<u8> = Vec::new();
let v = vec![0; 10];
for i in &v {
println!("Reference to {}", i);
}
for point in fractal.iter() {
if *point == 0 {…}
}
Structs and enums
STRUCT
struct Color {r: i32, g: i32, b: i32 }
fn main() {
let mut color: Color = Color { r: 255, g: 0, b: 0 };
color.g = 255;
println!("r: {}, g: {}, b: {}", color.r, color.g, color.b);
}
ENUM
#[derive(Debug)]
enum OperationError {
DivisionByZero,
UnexpextedError,
Indetermination,
}
fn division(n: f64, d: f64) -> Result<f64, OperationError> {...}
Pattern matching
let x = 3;
match x {
1 => println!("one"),
2 | 3 => println!("two or three"),
x @ 4..10 => println!(“say {}”, x),
_ => println!("i can't count that much"),
}
Result<T, E>
To manage errors, we can use the type system:
enum Result<T, E> {
Ok(T),
Err(E)
}
// Result<T, String>
fn division(num: f64, den: f64) -> Result<f64, String> {
if den == 0.0 {
Err(“Error”)
} else {
Ok(num / den)
}
}
Ownership
Variable bindings imply there is an owner to an asset
fn foo() {
let v = vec![1, 2, 3];
}
1) v in scope: Vec<i32> is created
2) Vector lives in the heap
3) Scope ends: v is freed, heap
allocated vector is cleaned.
There is only one binding to any asset. Lifetimes and transferring
ownership must be considered.
fn read_vector(vec: Vec<i32>) {
println!("{:?}", vec);
}
fn main() {
let my_vector = vec!(1, 3, 5, 7);
read_vector(my_vector);
println!("{:?}", my_vector); // error
}
Ownership
Give back ownership:
fn read_vector(vec: Vec<i32>) -> Vec<i32> {
println!("{:?}", vec);
vec
}
Borrowing (pass by reference):
fn read_vector(vec: &Vec<i32>) {
println!("{:?}", vec);
}
fn main() {
let my_vector = vec!(1, 3, 5, 7);
...
}
Ownership
Mutable reference: &mut
fn add_to_vector(vec: &mut Vec<i32>) {
vec.push(10);
}
fn main() {
let mut my_vector = vec!(1, 3, 5, 7);
add_to_vector(&mut my_vector);
println!("{:?}", my_vector);
}
● Any borrow's scope may not last longer than the owner
● Can exist many immutable borrows, (&x)
● Only one mutable reference (&mut x)
Traits
// TRAIT: Tells about a functionality a type has to provide
trait Dimensional {
fn area(&self) -> i32;
}
// Function for any type that implements the Dimensional trait
fn print_area<T: Dimensional>(object: T) {
println!("Area: {}", object.area());
}
struct Rectangle {x1: i32, y1: i32, x2: i32, y2: i32,}
impl Dimensional for Rectangle {
fn area(&self) -> i32 {
(self.x2 - self.x1) * (self.y2 - self.y1)
}
}
fn main() {
let r = Rectangle { x1: 0, x2: 4, y1: 0, y2: 2, };
print_area(r);
}
Closures
● Anonymous functions
● Rust imposes less restrictions about type annotations:
● Argument types and return types can be inferred
● May be multi-line, with statements between { }
fn main() {
let multiply = |x, y| x * y;
let sum_squares = |x: i32, y: i32| -> i32 {
let x = x * x;
let y = y * y;
x + y
};
println!("{:?}", multiply(2, 3));
println!("{:?}", sum_squares(2, 3));
}
Threading (spawning)
● A thread can be spawned with thread::spawn
● Accepts a closure and returns a handle
● Handles can be error checked with the Result Enum
use std::thread;
fn main() {
let handle = thread::spawn(|| "Hello".to_string());
match handle.join() {
Ok(x) => println!("{}", x),
Err(e) => println!("{:?}", e),
}
}
Other features
● Foreign Function Interface in 2 directions:
● Can call C code into Rust
● Can call Rust into other programs
● Conditional compilation by passing flags and assisted by Cargo
[features]
secure-password = ["bcrypt"]
● Use of 'raw pointers' (marked as unsafe to the compiler)
let x = 5;
let raw = &x as *const i32;
let points_at = unsafe { *raw };
println!("raw points at {}", points_at);
Rust projects
● Maidsafe (http://maidsafe.net/)
“ MaidSafe is a fully decentralized platform on which
application developers can build decentralized applications”
● Crates.io (https://crates.io/)
A catalog with Rust crates
● Servo (https://github.com/servo/servo)
“Servo is a prototype web browser engine written in the Rust
language. It is currently developed on 64bit OS X, 64bit Linux,
Android, and Gonk (Firefox OS).”

More Related Content

What's hot

Android taipei 20160225 淺談closure
Android taipei 20160225   淺談closureAndroid taipei 20160225   淺談closure
Android taipei 20160225 淺談closure
Gance Zhi-Hong Zhu (朱智鴻)
 
Go a crash course
Go   a crash courseGo   a crash course
Go a crash course
Eleanor McHugh
 
Frsa
FrsaFrsa
Frsa
_111
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
Eleanor McHugh
 
C++totural file
C++totural fileC++totural file
C++totural file
halaisumit
 
C++ tutorial
C++ tutorialC++ tutorial
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
Eleanor McHugh
 
Doubly linklist
Doubly linklistDoubly linklist
Doubly linklist
ilsamaryum
 
Study of aloha protocol using ns2 network java proram
Study of aloha protocol using ns2 network java proramStudy of aloha protocol using ns2 network java proram
Study of aloha protocol using ns2 network java proram
Meenakshi Devi
 
Python Tidbits
Python TidbitsPython Tidbits
Python Tidbits
Mitchell Vitez
 
บทที่ 3 พื้นฐานภาษา Java
บทที่ 3 พื้นฐานภาษา Javaบทที่ 3 พื้นฐานภาษา Java
บทที่ 3 พื้นฐานภาษา Java
Itslvle Parin
 
言語の設計判断
言語の設計判断言語の設計判断
言語の設計判断
nishio
 
AST + Better Reflection (PHP Benelux 2016 Unconference)
AST + Better Reflection (PHP Benelux 2016 Unconference)AST + Better Reflection (PHP Benelux 2016 Unconference)
AST + Better Reflection (PHP Benelux 2016 Unconference)
James Titcumb
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
Noritada Shimizu
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
Baruch Sadogursky
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Hans Höchtl
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
Mohammad Shaker
 
Coding with Vim
Coding with VimCoding with Vim
Coding with Vim
Enzo Wang
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
Yandex
 
Introduzione a C#
Introduzione a C#Introduzione a C#
Introduzione a C#
Lorenz Cuno Klopfenstein
 

What's hot (20)

Android taipei 20160225 淺談closure
Android taipei 20160225   淺談closureAndroid taipei 20160225   淺談closure
Android taipei 20160225 淺談closure
 
Go a crash course
Go   a crash courseGo   a crash course
Go a crash course
 
Frsa
FrsaFrsa
Frsa
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
C++totural file
C++totural fileC++totural file
C++totural file
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
 
Doubly linklist
Doubly linklistDoubly linklist
Doubly linklist
 
Study of aloha protocol using ns2 network java proram
Study of aloha protocol using ns2 network java proramStudy of aloha protocol using ns2 network java proram
Study of aloha protocol using ns2 network java proram
 
Python Tidbits
Python TidbitsPython Tidbits
Python Tidbits
 
บทที่ 3 พื้นฐานภาษา Java
บทที่ 3 พื้นฐานภาษา Javaบทที่ 3 พื้นฐานภาษา Java
บทที่ 3 พื้นฐานภาษา Java
 
言語の設計判断
言語の設計判断言語の設計判断
言語の設計判断
 
AST + Better Reflection (PHP Benelux 2016 Unconference)
AST + Better Reflection (PHP Benelux 2016 Unconference)AST + Better Reflection (PHP Benelux 2016 Unconference)
AST + Better Reflection (PHP Benelux 2016 Unconference)
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
Coding with Vim
Coding with VimCoding with Vim
Coding with Vim
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
Introduzione a C#
Introduzione a C#Introduzione a C#
Introduzione a C#
 

Similar to Short intro to the Rust language

Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
Kamil Toman
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
Yashpatel821746
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Yashpatel821746
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
Yashpatel821746
 
Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
sangam biradar
 
Briefly Rust
Briefly RustBriefly Rust
Briefly Rust
Daniele Esposti
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184
Mahmoud Samir Fayed
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
Knoldus Inc.
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
Pedro Rodrigues
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ahmed Salama
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
gkgaur1987
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
Tanwir Zaman
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
Jaehue Jang
 
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
Little Tukta Lita
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
pramode_ce
 
Golang
GolangGolang
Golang
Felipe Mamud
 
Beyond javascript using the features of tomorrow
Beyond javascript   using the features of tomorrowBeyond javascript   using the features of tomorrow
Beyond javascript using the features of tomorrow
Alexander Varwijk
 
C# programming
C# programming C# programming
C# programming
umesh patil
 
Erlang bootstrap course
Erlang bootstrap courseErlang bootstrap course
Erlang bootstrap course
Martin Logan
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 

Similar to Short intro to the Rust language (20)

Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
 
Briefly Rust
Briefly RustBriefly Rust
Briefly Rust
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
 
Golang
GolangGolang
Golang
 
Beyond javascript using the features of tomorrow
Beyond javascript   using the features of tomorrowBeyond javascript   using the features of tomorrow
Beyond javascript using the features of tomorrow
 
C# programming
C# programming C# programming
C# programming
 
Erlang bootstrap course
Erlang bootstrap courseErlang bootstrap course
Erlang bootstrap course
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 

Recently uploaded

Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 

Recently uploaded (20)

Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 

Short intro to the Rust language

  • 2. About Rust ● New systems programming language by Mozilla. ● Designed to write secure code: ● Memory safety ● Thread safety ● Performance similar to C++
  • 3. Hello, world! fn main() { println!(“Hello, world!”); } $ rustc hello.rs $ ./hello Hello, world!
  • 4. Cargo Cargo.toml [package] name = "program" version = "0.1.0" authors = ["John D <john.d@test.com>"] [features] default = [ ] [dependencies] num = "0.1.27" Commands $ cargo build $ cargo test $ cargo run $ cargo new title [--bin] Tool used for downloading dependencies, building dependencies and building our program.
  • 5. Syntax fn increase(x: i32) -> i32 { x + 1 } fn swap(tuple: (i32, i32)) -> (i32, i32) { let (x, y) = tuple; (y, x) } fn main() { println!("{}", increase(10)); let my_tuple = (10, 20); println!("{:?}", swap(my_tuple)); } $ rustc syntax.rs $ ./syntax 11 (20, 10)
  • 6. Variable bindings A 'let' expression is a pattern: let(x, y) = (42, 24); // x = 42, y = 24 Variable bindings are immutable by default: let x = 42; x = 10;// error let mut x = 42; Type inference: let x: i32 = 10; // Same as let x = 10;
  • 7. Stack and Heap fn main() { let x = Box::new(5); let y = 42; let z = &x; } Box<T> implements Drop, it is freed when it goes out of scope Address Name Value 2^30 ... 5 2 z → 0 1 y 42 0 x → 2^30
  • 8. Vector ● Provided by the std library ● Growable (dynamic) ● Can implement any type: Vec<T> let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32> let mut my_vector: Vec<u8> = Vec::new(); let v = vec![0; 10]; for i in &v { println!("Reference to {}", i); } for point in fractal.iter() { if *point == 0 {…} }
  • 9. Structs and enums STRUCT struct Color {r: i32, g: i32, b: i32 } fn main() { let mut color: Color = Color { r: 255, g: 0, b: 0 }; color.g = 255; println!("r: {}, g: {}, b: {}", color.r, color.g, color.b); } ENUM #[derive(Debug)] enum OperationError { DivisionByZero, UnexpextedError, Indetermination, } fn division(n: f64, d: f64) -> Result<f64, OperationError> {...}
  • 10. Pattern matching let x = 3; match x { 1 => println!("one"), 2 | 3 => println!("two or three"), x @ 4..10 => println!(“say {}”, x), _ => println!("i can't count that much"), }
  • 11. Result<T, E> To manage errors, we can use the type system: enum Result<T, E> { Ok(T), Err(E) } // Result<T, String> fn division(num: f64, den: f64) -> Result<f64, String> { if den == 0.0 { Err(“Error”) } else { Ok(num / den) } }
  • 12. Ownership Variable bindings imply there is an owner to an asset fn foo() { let v = vec![1, 2, 3]; } 1) v in scope: Vec<i32> is created 2) Vector lives in the heap 3) Scope ends: v is freed, heap allocated vector is cleaned. There is only one binding to any asset. Lifetimes and transferring ownership must be considered. fn read_vector(vec: Vec<i32>) { println!("{:?}", vec); } fn main() { let my_vector = vec!(1, 3, 5, 7); read_vector(my_vector); println!("{:?}", my_vector); // error }
  • 13. Ownership Give back ownership: fn read_vector(vec: Vec<i32>) -> Vec<i32> { println!("{:?}", vec); vec } Borrowing (pass by reference): fn read_vector(vec: &Vec<i32>) { println!("{:?}", vec); } fn main() { let my_vector = vec!(1, 3, 5, 7); ... }
  • 14. Ownership Mutable reference: &mut fn add_to_vector(vec: &mut Vec<i32>) { vec.push(10); } fn main() { let mut my_vector = vec!(1, 3, 5, 7); add_to_vector(&mut my_vector); println!("{:?}", my_vector); } ● Any borrow's scope may not last longer than the owner ● Can exist many immutable borrows, (&x) ● Only one mutable reference (&mut x)
  • 15. Traits // TRAIT: Tells about a functionality a type has to provide trait Dimensional { fn area(&self) -> i32; } // Function for any type that implements the Dimensional trait fn print_area<T: Dimensional>(object: T) { println!("Area: {}", object.area()); } struct Rectangle {x1: i32, y1: i32, x2: i32, y2: i32,} impl Dimensional for Rectangle { fn area(&self) -> i32 { (self.x2 - self.x1) * (self.y2 - self.y1) } } fn main() { let r = Rectangle { x1: 0, x2: 4, y1: 0, y2: 2, }; print_area(r); }
  • 16. Closures ● Anonymous functions ● Rust imposes less restrictions about type annotations: ● Argument types and return types can be inferred ● May be multi-line, with statements between { } fn main() { let multiply = |x, y| x * y; let sum_squares = |x: i32, y: i32| -> i32 { let x = x * x; let y = y * y; x + y }; println!("{:?}", multiply(2, 3)); println!("{:?}", sum_squares(2, 3)); }
  • 17. Threading (spawning) ● A thread can be spawned with thread::spawn ● Accepts a closure and returns a handle ● Handles can be error checked with the Result Enum use std::thread; fn main() { let handle = thread::spawn(|| "Hello".to_string()); match handle.join() { Ok(x) => println!("{}", x), Err(e) => println!("{:?}", e), } }
  • 18. Other features ● Foreign Function Interface in 2 directions: ● Can call C code into Rust ● Can call Rust into other programs ● Conditional compilation by passing flags and assisted by Cargo [features] secure-password = ["bcrypt"] ● Use of 'raw pointers' (marked as unsafe to the compiler) let x = 5; let raw = &x as *const i32; let points_at = unsafe { *raw }; println!("raw points at {}", points_at);
  • 19. Rust projects ● Maidsafe (http://maidsafe.net/) “ MaidSafe is a fully decentralized platform on which application developers can build decentralized applications” ● Crates.io (https://crates.io/) A catalog with Rust crates ● Servo (https://github.com/servo/servo) “Servo is a prototype web browser engine written in the Rust language. It is currently developed on 64bit OS X, 64bit Linux, Android, and Gonk (Firefox OS).”