This document provides an introduction to the Rust programming language. It discusses Rust's memory safety features, variable bindings, functions, control flow statements like if/else and loops, data types like tuples and vectors, and borrowing rules. It also covers Rust concepts like ownership, slices, pattern matching, and destructuring. Examples are provided to demonstrate various Rust language features.
Functions being first-class citizens in JavaScript offers developers a tremendous amount power and
flexibilty. However, what good is all this power if you don't know how to harness it?
This talk will provide a thorough examination of JavaScript functions. Topics
that will be covered in this talk are:
* Functions are objects
* Execution Context and the Scope Chain
* Closures
* Modifying Context
* The Various Forms of Functions.
Attendees will leave this talk understanding the power of JavaScript functions and the knowledge to apply new
techiques that will make their JavaScript cleaner, leaner and more maintainable.
Functions being first-class citizens in JavaScript offers developers a tremendous amount power and
flexibilty. However, what good is all this power if you don't know how to harness it?
This talk will provide a thorough examination of JavaScript functions. Topics
that will be covered in this talk are:
* Functions are objects
* Execution Context and the Scope Chain
* Closures
* Modifying Context
* The Various Forms of Functions.
Attendees will leave this talk understanding the power of JavaScript functions and the knowledge to apply new
techiques that will make their JavaScript cleaner, leaner and more maintainable.
Rust
Why do you care about Rust? Who has the time to learn all these new languages? It seems like a new one is popping up every other week and this trend is growing at an exponential rate. Good news, a fair number of them are crafted really well and efficiently solve specific problems. Bad news, how do you keep up with all of this, let alone decide which languages to include in your companies technology portfolio.
Despite the challenges of all these new languages, a majority of developers are intrigued about the idea of becoming a polyglot, but don't know where to begin or don't have the time. In my polyglot travels, there is one language of late that is the sure-fire answer to the above questions, Rust.
In this talk I’ll explore the value behind becoming more polyglotic as a developer, how to pick languages to learn, and then dive deep in the the language of Rust. Which in my opinion, is hands down the best up and coming languages to learn.
About the Presenter
Anthony Broad-Crawford has been a developer since the year 2000 with a short side stint as a semi-professional poker player. Since his transition to software development Anthony has...
1. Built 8 patent receiving technologies
2. Founded two global companies
3. Been a CTO (3x), CPO (1x), and CEO (1x)
and is currently the CTO at Fooda where he manages product, user experience, and engineering. Fooda is predominantly web and mobile technology company focused on bringing great & healthy food from the best restaurant's to people while at the office.
Through his career, in production applications Anthony has used Ruby, Java, Jave (Android), Objective-C and Swift, .NET, Erlang, Scala, Node.JS, LISP, Smalltalk, and even assembly, with his recent favorite, Rust . No, not all at the same time in the same application.
Anthony now spends his time building great teams, that leverage great technology, to build great products, but still looks to codes every chance he can get :)
"Delegates, Delegates everywhere" Владимир МироновAvitoTech
Поговорим про delegated properties и все, что с ними связано. Узнаем, зачем они нужны, какие delegated properties предоставляет стандартная библиотека, напишем несколько своих и рассмотрим более сложные примеры, которые могут быть полезны в мире android-разработки. Мы также посмотрим, во что delegated properties превращаются во время компиляции, и какие сюрпризы нас могут ожидать.
Will talk about kotlin the language and new concepts introduced in the language including functional programming.
And how to use your springframework knowlege to write more concise and elegant backend systems.
We will demo a backend written in spring boot and kotlin and will see how it is so easy to interoperate between java and kotlin code.
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
Concurrent programming with Celluloid (MWRC 2012)tarcieri
Threads versus events: which should you choose? How about both? In this talk you'll learn about the Celluloid concurrency framework, which combines OOP and the Actor Model to give you concurrent Ruby objects. You'll also learn about how Celluloid lets you combine blocking I/O and asynchronous evented I/O, offering you all the benefits of EventMachine without the restrictions of a single event loop. The talk will also provide a brief introduction to DCell, a distributed extension to Celluloid.
"Kotlin и rx в android" Дмитрий Воронин (Avito)AvitoTech
Rx и Kotlin стали самыми модными трендами Android разработки в последнее время. Мы выпустили два приложения с архитектурой, построенной вокруг Rx, где нет ни одной строки на Java. Насколько удобно работать с этими инструментами? В своём докладе я расскажу, с какими трудностями мы столкнулись, как их победили, а также продемонстрирую несколько крутых и несложных подходов к разработке на этом стеке.
Rust
Why do you care about Rust? Who has the time to learn all these new languages? It seems like a new one is popping up every other week and this trend is growing at an exponential rate. Good news, a fair number of them are crafted really well and efficiently solve specific problems. Bad news, how do you keep up with all of this, let alone decide which languages to include in your companies technology portfolio.
Despite the challenges of all these new languages, a majority of developers are intrigued about the idea of becoming a polyglot, but don't know where to begin or don't have the time. In my polyglot travels, there is one language of late that is the sure-fire answer to the above questions, Rust.
In this talk I’ll explore the value behind becoming more polyglotic as a developer, how to pick languages to learn, and then dive deep in the the language of Rust. Which in my opinion, is hands down the best up and coming languages to learn.
About the Presenter
Anthony Broad-Crawford has been a developer since the year 2000 with a short side stint as a semi-professional poker player. Since his transition to software development Anthony has...
1. Built 8 patent receiving technologies
2. Founded two global companies
3. Been a CTO (3x), CPO (1x), and CEO (1x)
and is currently the CTO at Fooda where he manages product, user experience, and engineering. Fooda is predominantly web and mobile technology company focused on bringing great & healthy food from the best restaurant's to people while at the office.
Through his career, in production applications Anthony has used Ruby, Java, Jave (Android), Objective-C and Swift, .NET, Erlang, Scala, Node.JS, LISP, Smalltalk, and even assembly, with his recent favorite, Rust . No, not all at the same time in the same application.
Anthony now spends his time building great teams, that leverage great technology, to build great products, but still looks to codes every chance he can get :)
"Delegates, Delegates everywhere" Владимир МироновAvitoTech
Поговорим про delegated properties и все, что с ними связано. Узнаем, зачем они нужны, какие delegated properties предоставляет стандартная библиотека, напишем несколько своих и рассмотрим более сложные примеры, которые могут быть полезны в мире android-разработки. Мы также посмотрим, во что delegated properties превращаются во время компиляции, и какие сюрпризы нас могут ожидать.
Will talk about kotlin the language and new concepts introduced in the language including functional programming.
And how to use your springframework knowlege to write more concise and elegant backend systems.
We will demo a backend written in spring boot and kotlin and will see how it is so easy to interoperate between java and kotlin code.
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
Concurrent programming with Celluloid (MWRC 2012)tarcieri
Threads versus events: which should you choose? How about both? In this talk you'll learn about the Celluloid concurrency framework, which combines OOP and the Actor Model to give you concurrent Ruby objects. You'll also learn about how Celluloid lets you combine blocking I/O and asynchronous evented I/O, offering you all the benefits of EventMachine without the restrictions of a single event loop. The talk will also provide a brief introduction to DCell, a distributed extension to Celluloid.
"Kotlin и rx в android" Дмитрий Воронин (Avito)AvitoTech
Rx и Kotlin стали самыми модными трендами Android разработки в последнее время. Мы выпустили два приложения с архитектурой, построенной вокруг Rx, где нет ни одной строки на Java. Насколько удобно работать с этими инструментами? В своём докладе я расскажу, с какими трудностями мы столкнулись, как их победили, а также продемонстрирую несколько крутых и несложных подходов к разработке на этом стеке.
Explorando el Diseño de la Memoria en RustGermán Küber
Esta presentación, creada por Germán Kúber, ofrece una inmersión profunda en la organización y gestión de la memoria en la programación Rust, abordando desde la disposición de la memoria hasta los conceptos avanzados como el manejo del heap y el stack, y cómo Rust optimiza el uso de la memoria en tiempo de ejecución.
Rust — это современный, практический, быстрый и безопасный язык программирования. Некоторые говорят, что Rust — это как C++, если бы его писал человек, знающий Haskell.
Система типов Rust решает главную проблему C++ — небезопасность. C++ очень легко сделать ошибки, которые приведут к поломкам (например, use after free). Rust позволяет писать безопасный код, сохраняя при этом выразительность и околонулевые накладные расходы C++. В докладе будут подробно описаны механизмы языка, которые контролируют безопасность программы.
Хотя в данный момент Rust ещё не подходит для использования в продакшне, его всё равно стоит изучать. Во-первых, потому что это очень интересный подход к программированию, а во-вторых, потому что через несколько лет для разработки требовательных к ресурсам программ будет необходим именно Rust или другой похожий инструмент.
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовYandex
Последние 15 лет между разработчиками на Java и на C++ ведётся спор о том, какой язык программирования хуже — Java или C++. Программы на C++ глючат, падают, и в них утекает память. Программы на Java тормозят и требуют слишком много памяти.
Rust — новый язык программирования, разрабатываемый компанией Mozilla — решает проблемы Java и C++: программы, написанные на Rust, одновременно быстрые и безопасные. Rust является таким же низкоуровневым, close-to-metal языком программирования, как и C++, однако в язык встроены конструкции, позволяющие на этапе компиляции доказывать, что в программе не случится обращения к неинициализированной памяти (механизм borrowed pointers). Большая часть моего рассказа будет посвящена описанию этого механизма.
FITC events. For digital creators.
Save 10% off ANY FITC event with discount code 'slideshare'
See our upcoming events at www.fitc.ca
An Intro To ES6
with Grant Skinner
OVERVIEW
ECMAScript 6 is the approved and published standard for the next version of JavaScript. It offers new syntax and language features that provide new ways of tackling coding problems, and increase your productivity.
This session will introduce ES6 and delve into many of the new features of the language. It will also cover real-world use, including transpilers, runtimes, and browser support.
OBJECTIVE
Create confidence in evaluating and getting started using ES6.
TARGET AUDIENCE
JavaScript developers.
ASSUMED AUDIENCE KNOWLEDGE
JavaScript.
FOUR THINGS AUDIENCE MEMBERS WILL LEARN
Status of ES6
How to get started with ES6
ES6 feature overview
Practical considerations for adopting ES6
Rust is a emerging system language with the speed of C/C++, the ergonomics of a functional language and the safety of a modern dynamic language. In this presentation I’ll expose the main feature of the language which make it distinctive and a good choice for fats and reliable software.
A Recovering Java Developer Learns to GoMatt Stine
As presented at OSCON 2014.
The Go programming language has emerged as a favorite tool of DevOps and cloud practitioners alike. In many ways, Go is more famous for what it doesn’t include than what it does, and co-author Rob Pike has said that Go represents a “less is more” approach to language design.
The Cloud Foundry engineering teams have steadily increased their use of Go for building components, starting with the Router, and progressing through Loggregator, the CLI, and more recently the Health Manager. As a “recovering-Java-developer-turned-DevOps-junkie” focused on helping our customers and community succeed with Cloud Foundry, it became very clear to me that I needed to add Go to my knowledge portfolio.
This talk will introduce Go and its distinctives to Java developers looking to add Go to their toolkits. We’ll cover Go vs. Java in terms of:
* type systems
* modularity
* programming idioms
* object-oriented constructs
* concurrency
Rust is a emerging system language with the speed of C/C++, the ergonomics of a functional language and the safety of a modern dynamic language. In this presentation I’ll expose the main feature of the language which make it distinctive and a good choice for fats and reliable software
Gopher Labs brings you tutorials that help you get hands-on experience using Golang. Here you will find complete documentation of labs and tutorials that will help you, no matter if you are a beginner, SysAdmin, IT Pro or Developer. Yes, you read it right ! Its $0 learning platform. You don’t need any infrastructure. Most of the tutorials runs on Play with GO Platform. This is a free browser based learning platform for you. Hence, we have everything ready for you to get started with.
Introducing Pico - A Deep Learning Platform using Docker & IoT - Sangam Biradarsangam biradar
presented at https://events.docker.com/events/details/docker-hyderabad-presents-docker-hyderabad-meetup-19-docker-kubernetes-iot-docker101-workshop/
at MobileIron India
6th Floor, Western Pearl, Survey No. 13, Kondapur, Hitech City Rd, Kothaguda
Hyderabad, 500084
date : 14 sept 19
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
2. Sangam Biradar
Blogger :- engineItops.com
Founder :- KubeDaily
- Docker Community Leader , B’lore
- Traefik Ambassador
- Okteto Community Lead , India
- Course Author:- “Lightweight Kubernetes – K3s”
Packt Publication UK
@BiradarSangam | @KubeDaily
3. Programming language Rust
● Safe and efficient system programming
● Characteristics
○ Procedural language, abstract data type, closures
○ Static typing, strong type inference
○ Safe pointer operations
○ Parallel programming with message passing / shared memory
4. ● Set up
● Online compiler: http://play.rust-lang.org/
● Install Rust compiler to your own environment, if
you want to do it offline.
Setup Rust
5. ● curl -sSf https://static.rust-lang.org/rustup.sh | sh
● Mac / Linux: Install with rustup as above
● Windows: Installer is also available
Compiler installation
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
7. % cargo new --bin hello_world
% cd hello_world
% cargo build
% cargo run
"Hello, world!" with Cargo
• new command populate project folders
• build command will build binary files
• run command will build project and run it
8. fn main() {
println! ("Hello, world!");
}
Hello, world
Rust Playground
Cheers! 1st Rust Program Executed Successful !
9. fn main() {
println!("Hello, world!");
}
main function: entry point
• Rust programs (not libraries) require main function as
their entry point
• fn is a statement to define functions
10. fn main() {
println!("Hello, world!");
}
println!
- A macro to output literals into consoles
- We can embed expressions
11. fn main() {
let name = ”Sangam";
println!("Hello, {}", name);
}
Variables
- We can use variables only if we declare them
- let: a statement to declare variables
Rust Playground
12. fn main() {
let name = ”sangam";
println!("Hello, {}", name);
}
Variable bindings
Rust Playground
13. fn main() {
let name = "sangam";
println!("Hello, {}", name);
name = "biradar";
println!("Hello, {}", name);
}
Immutable values
•Build error occurs when we build the this code
•We can not change the bound value
14. fn main() {
let name = "Sangam";
println!("Hello, {}", name);
let name = "Biradar";
println!("Hello, {}", name);
}
Make another variable binding
• In this case, we will not face a build error
• We make another variable binding with a second let
statement
15. fn main() {
let mut name = "Sangam";
println!("Hello, {}", name);
name = "Rust";
println!("Hello, {}", name);
}
mut: mutable variables declaration
Rust Playground
We can change binded values when their variables declared with mut keyword
16. fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!("1 + 1 = {}", add(1, 1));
println!("13 + 23 = {}", add(13, 23));
}
Function declarations
We need to put type annotations to arguments and
return values
17. fn add(a: i32, b: i32) -> i32 {
let answer: i32;
answer = a + b;
answer
}
fn main() {
println!("1 + 1 = {}", add(1, 1));
println!("13 + 23 = {}", add(13, 23));
}
Type annotation to variables
• variable_name:type
• We can omit type annotations when compiler can infer
types
18. fn add(a: i32, b: i32) -> i32 {
a + b
}
fn sub(a: i32, b: i32) -> i32 {
return a - b;
}
fn main() {
println!("1 + 1 = {}", add(1, 1));
println!("13 + 23 = {}", add(13, 23));
println!("23 - 13 = {}", sub(23, 13));
}
Return values
• Functions return the evaluated values of their last
expression
• We can also describe return values with return
statement explicitely
• The return values are annotated as -> type
20. let a = [1, 2, 3]; // a: [i32; 3]
let mut m = [1, 2, 3]; // m: [i32; 3]
Access to each item with its index
• Fixed length, every item belong to same type
• Annotated as [type; size]
• We need to declare a mutable object when we want to
change its items
Arrays
fn main() {
let a = [1, 2, 3];
println!("0th element {}", a[0]);
println!("1th element : {}", a[1]);
println!("2th element: {}", a[2]);
}
21. fn main() {
let a = [1, 2, 3];
println!("# of items in a: {}", a.len());
}
len() to refer # of items
We can refer to the arrays length by calling its len method
22. fn main() {
let a = [0, 1, 2, 3, 4, 5];
let middle = &a[1..4];
println!("a.len() = {}", a.len());
println!("middle.len() = {}", middle.len());
}
Slice: reference to another structure
Create an slice as &array_name[start_index..end_index]
23. let x = (1, "hello"); // x: (i32, &str)
let mut p1 = (1, 2); // p1: (i32, i32)
let p2 = (3, 4); // p2: (i32, i32)
p1 = p2;
Tuple: fixed size ordered list
•We can create a fixed size ordered list as tuple
•Paris, triples, etc can be represented as tuples
•A tuple can be annotated as (type of first element, type
of second element, ...)
24. let p = (1, 2, 3);
let (x, y, z) = p;
let x = p.0;
let y = p.1;
let z = p.2;
Access to tuple elements
•We can access each field by destructuring
•Also each items can also be accessed with their
indexes
26. fn main(){
let x = 5;
if x > 10 {
println!("x > 10")
}else if x > 0{
println!("x < x <= 10")
}else{
println!("x < 0")
};
}
Conditional branch
We need not to write condition within parenthesis
27. fn main(){
let x = 5;
let y = if x > 0{
1
}else{
0
};
println!("y = {}", y);
}
if expression
if is a expression, not statement in Rust So, it has an
evaluation value
28. fn main() {
let mut i = 0;
loop{
i = i +1;
println!("{} sangam biradar ", i);
if i > 9{
break;
}
}
}
loop statement: infinite loop
29. fn main() {
let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}
}
while statement
We do not need parenthesize
loop conditions as well
30. fn main() {
for x in 0..10 {
println!("{}", x); // x: i32
}
}
for statement: scan items over iterators
0..10: an object literal, which represents a list consisting
of integers within the specified range
31. for (index, value) in (0..10).enumerate() {
println!("index = {}, value = {}", index, value);
}
enumerate method
• We can refer to the index value of each iteration by calling enumerate method
32. fn main() {
let v = vec![1, 2, 3, 4, 5];
let zeroes = vec![0; 10];
for i in 0..v.len() {
println!("v[{}] = {}", i, v[i]);
}
for i in 0..zeroes.len() {
println!("zeroes[{}] = {}", i, zeroes[i]);
}
}
Vector: variable length list
Vec more Details:
https://doc.rust-lang.org/stable/std/vec/
Created with vec! macro
33. fn main() {
let v = vec![1, 2, 3, 4, 5];
for (index, value) in v.iter().enumerate() {
println!("v[{}] = {}", index, value);
}
}
Scaning a vector
Create an iterator by calling vector's iter method
34. fn main() {
let v = vec![1, 2, 3, 4, 5];
let result = v.iter().filter(|&n| n % 2 != 0).map(|n| n + 1);
for (index, value) in result.enumerate() {
println!("result[{}]:{}", index, value);
}
}
filter / map
An iterator has several methods to create other iterators such as filter and map
35. fn main() {
let v = vec![1, 2, 3];
println!("v[1] = {}", v[1]);
let v2 = v;
println!("v2[1] = {}", v2[1]);
println!("v[1] = {}", v[1]);
}
Ownership and move semantics
This code cannot be compiled
Because ownership against vec![1, 2, 3] is moved
from v to v2 Variable binding means "binded value
is a possesion of the biding variable"
36. fn main(){
let x = 10;
println!("x = {}", x);
let y = x;
println!("y = {}", y);
println!("x = {}", x);
}
Copy trait
Some values (e.g. i32) copy themselves when new
variable bindings are created
• x and y do not bind the same object
• but, they bind different and equivalent objects
Their type implements Copy trait
37. fn sum_vec(memo:Vec<i32>)->i32{
let mut sum = 0;
for i in memo.iter(){
sum = sum + i;
}
sum
}
fn main() {
let v = vec![1, 2, 3];
println!("sum = {}",sum_vec(v));
println!("sum = {}",sum_vec(v));
}
Owenership transfer via function calls
Causes build error
Ownership of vec![1, 2, 3] has been moved to the first
argument of sum_vec, when its first call
38. fn sum_vec(memo:Vec<i32>)->(i32, Vec<i32>){
let mut sum = 0;
for i in memo.iter(){
sum = sum + i;
}
(sum, memo)
}
fn main() {
let v = vec![1, 2, 3];
let (sum, v) = sum_vec(v);
println!("sum = {}", sum);
let (sum, _) = sum_vec(v);
println!("sum = {}", sum);
}
Return arguments' ownership with tuples
39. fn sum_vec(memo: &Vec<i32>) -> i32 {}
fn main() {
let v = vec![1, 2, 3];
println!("sum = {}", sum_vec(&v));
println!("sum = {}", sum_vec(&v));
}
Reference
• We can get a reference to a value by specifying &
before its name
• References are annoted as &Typename
• Functions borrow values' ownership when their
reference are passed
• The ownership automatically returns when borrwing
function returns
41. fn foo(v: &mut Vec<i32>){
v.push(5);
}
fn main(){
let mut v = vec![];
println!("v.len() = {}", v.len());
foo(&mut v);
println!("v.len() = {}", v.len());
}
Mutable borrowed values
• We can get mutable references with &mut
• Only if the values are mutable
42. ● We can create one ore more read only references (&)
● The # of mutable reference is limited to 1 at most(&mut)
○ Only 1 thread can be change the state
○ This limitation is set to avoid race conditions
Rules of borrowing
43. fn main() {
let x = 5;
let label = match x {
1 => "sangam",
2 => "rustlab",
3 => "labs",
_ => "kubedaily",
};
println!("{} : {}", x, label);
}
_ matches the uncovered cases
44. fn main(){
let x = 5;
let label = match x {
1 => ”sangam",
2 => "2",
3 => "San",
4 | 5 | 6 | 7 | 8 | 9 => "single digit",
_ => "Other",
};
println!("{} :{}", x, label);
}
| : union of patterns
•| matches multiple patterns at once
45. fn main(){
let x = (1, 5);
let label = match x {
(0, 0) => "zero",
(1, 0) | (0, 1) => "unit",
(1, _) => "x is 1",
(_, 1) => "y is 1",
_ => "Other"
};
println!("{}", label);
}
Destructuring
46. let car = “red “
let red = &car[0..5];
str: how to create a slice from a static text
47. We Will Contd Next topics in future Session
https://discord.gg/aU3yAmFJoin RustLabs Community:-
https://rustlabs.kubedaily.com/
48. THANKS!Do you have any questions?
@KubeDaily
Sangam Biradar
@Biradar Sangam
Rustlabs.kubedaily.com