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 :)
Rust: Reach Further (from QCon Sao Paolo 2018)nikomatsakis
Rust is a new programming language that is growing rapidly. Rust's goal is to support a high-level coding style while offering performance comparable to C and C++ as well as minimal runtime requirements -- it does not require a runtime or garbage collector, and you can even choose to forego the standard library. At the same time, Rust offers strong support for parallel programming, including guaranteed freedom from data-races (something that GC’d languages like Java or Go do not provide).
Rust’s slim runtime requirements make it an ideal choice for integrating into other languages and projects. Anywhere that you could integrate a C or C++ library, you can choose to use Rust instead. Mozilla, for example, has rewritten a portion of the Firefox web browser in Rust -- while keeping the rest in C++. There are also projects for writing native extensions to Python, Ruby, and Node in Rust, as well as a recent effort to have the Rust compiler generate WebAssembly.
This talk will cover some of the highlights of Rust's design, and show how Rust's type system not only supports different parallel styles but also encourages users to write code that is amenable to parallelization. I'll also talk a bit about some of the experiences of using Rust in production, as well as how to integrate Rust into existing projects written in different languages.
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 :)
Rust: Reach Further (from QCon Sao Paolo 2018)nikomatsakis
Rust is a new programming language that is growing rapidly. Rust's goal is to support a high-level coding style while offering performance comparable to C and C++ as well as minimal runtime requirements -- it does not require a runtime or garbage collector, and you can even choose to forego the standard library. At the same time, Rust offers strong support for parallel programming, including guaranteed freedom from data-races (something that GC’d languages like Java or Go do not provide).
Rust’s slim runtime requirements make it an ideal choice for integrating into other languages and projects. Anywhere that you could integrate a C or C++ library, you can choose to use Rust instead. Mozilla, for example, has rewritten a portion of the Firefox web browser in Rust -- while keeping the rest in C++. There are also projects for writing native extensions to Python, Ruby, and Node in Rust, as well as a recent effort to have the Rust compiler generate WebAssembly.
This talk will cover some of the highlights of Rust's design, and show how Rust's type system not only supports different parallel styles but also encourages users to write code that is amenable to parallelization. I'll also talk a bit about some of the experiences of using Rust in production, as well as how to integrate Rust into existing projects written in different languages.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/1mn7lIO.
Aaron Turon explains Rust's core notion of “ownership” and shows how Rust uses it to guarantee thread safety, amongst other things. He also talks about how Rust goes beyond addressing the pitfalls of C++ to do something even more exciting: unlock a new generation of systems programmers by providing a safe, high-level experience -- while never compromising on performance. Filmed at qconsf.com.
Aaron Turon manages the Rust team at Mozilla Research. His background is in low-level concurrency and programming language design.
This presentation was held at the Stockholm Rust Meetup in September 2019.
This is a brief introduction to Rust and highlights some of the problems with C++ that it attempts to solve. It also contain a brief introduction to the ownership model and the borrow checker that Rust uses.
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовYandex
Последние 15 лет между разработчиками на Java и на C++ ведётся спор о том, какой язык программирования хуже — Java или C++. Программы на C++ глючат, падают, и в них утекает память. Программы на Java тормозят и требуют слишком много памяти.
Rust — новый язык программирования, разрабатываемый компанией Mozilla — решает проблемы Java и C++: программы, написанные на Rust, одновременно быстрые и безопасные. Rust является таким же низкоуровневым, close-to-metal языком программирования, как и C++, однако в язык встроены конструкции, позволяющие на этапе компиляции доказывать, что в программе не случится обращения к неинициализированной памяти (механизм borrowed pointers). Большая часть моего рассказа будет посвящена описанию этого механизма.
Rust — это современный, практический, быстрый и безопасный язык программирования. Некоторые говорят, что Rust — это как C++, если бы его писал человек, знающий Haskell.
Система типов Rust решает главную проблему C++ — небезопасность. C++ очень легко сделать ошибки, которые приведут к поломкам (например, use after free). Rust позволяет писать безопасный код, сохраняя при этом выразительность и околонулевые накладные расходы C++. В докладе будут подробно описаны механизмы языка, которые контролируют безопасность программы.
Хотя в данный момент Rust ещё не подходит для использования в продакшне, его всё равно стоит изучать. Во-первых, потому что это очень интересный подход к программированию, а во-вторых, потому что через несколько лет для разработки требовательных к ресурсам программ будет необходим именно Rust или другой похожий инструмент.
Presentación de la charla impartida en el meetup de Python Madrid sobre Asincronía en Python https://www.meetup.com/es-ES/python-madrid/events/268111847/
University of Virginia
cs4414: Operating Systems
http://rust-class.org
Explicit vs. Automatic Memory Management
Garbage Collection, Reference Counting
Rust ownership types
For embedded notes, see: http://rust-class.org/class9-pointers-in-rust.html
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/1mn7lIO.
Aaron Turon explains Rust's core notion of “ownership” and shows how Rust uses it to guarantee thread safety, amongst other things. He also talks about how Rust goes beyond addressing the pitfalls of C++ to do something even more exciting: unlock a new generation of systems programmers by providing a safe, high-level experience -- while never compromising on performance. Filmed at qconsf.com.
Aaron Turon manages the Rust team at Mozilla Research. His background is in low-level concurrency and programming language design.
This presentation was held at the Stockholm Rust Meetup in September 2019.
This is a brief introduction to Rust and highlights some of the problems with C++ that it attempts to solve. It also contain a brief introduction to the ownership model and the borrow checker that Rust uses.
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовYandex
Последние 15 лет между разработчиками на Java и на C++ ведётся спор о том, какой язык программирования хуже — Java или C++. Программы на C++ глючат, падают, и в них утекает память. Программы на Java тормозят и требуют слишком много памяти.
Rust — новый язык программирования, разрабатываемый компанией Mozilla — решает проблемы Java и C++: программы, написанные на Rust, одновременно быстрые и безопасные. Rust является таким же низкоуровневым, close-to-metal языком программирования, как и C++, однако в язык встроены конструкции, позволяющие на этапе компиляции доказывать, что в программе не случится обращения к неинициализированной памяти (механизм borrowed pointers). Большая часть моего рассказа будет посвящена описанию этого механизма.
Rust — это современный, практический, быстрый и безопасный язык программирования. Некоторые говорят, что Rust — это как C++, если бы его писал человек, знающий Haskell.
Система типов Rust решает главную проблему C++ — небезопасность. C++ очень легко сделать ошибки, которые приведут к поломкам (например, use after free). Rust позволяет писать безопасный код, сохраняя при этом выразительность и околонулевые накладные расходы C++. В докладе будут подробно описаны механизмы языка, которые контролируют безопасность программы.
Хотя в данный момент Rust ещё не подходит для использования в продакшне, его всё равно стоит изучать. Во-первых, потому что это очень интересный подход к программированию, а во-вторых, потому что через несколько лет для разработки требовательных к ресурсам программ будет необходим именно Rust или другой похожий инструмент.
Presentación de la charla impartida en el meetup de Python Madrid sobre Asincronía en Python https://www.meetup.com/es-ES/python-madrid/events/268111847/
University of Virginia
cs4414: Operating Systems
http://rust-class.org
Explicit vs. Automatic Memory Management
Garbage Collection, Reference Counting
Rust ownership types
For embedded notes, see: http://rust-class.org/class9-pointers-in-rust.html
Do you want to learn Kotlin programming language from scratch? This is the 2nd episode of a simple course, focused on function and functional programming
Perl6 regular expression ("regex") syntax has a number of improvements over the Perl5 syntax. The inclusion of grammars as first-class entities in the language makes many uses of regexes clearer, simpler, and more maintainable. This talk looks at a few improvements in the regex syntax and also at how grammars can help make regex use cleaner and simpler.
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
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
5. // sums all the positive values in `v`
fn sum_pos(v: &[i32]) -> i32 {
let mut sum = 0;
for i in v.iter().filter(|i| **i > 0) {
sum += *i;
}
sum
}
High-level coding
3
6. // sums all the positive values in `v`
fn sum_pos(v: &[i32]) -> i32 {
let mut sum = 0;
for i in v.iter().filter(|i| **i > 0) {
sum += *i;
}
sum
}
High-level coding
3
Iterators.
Closures.
10. Safe
6
fn this_wont_compile(v: &mut Vec<i32>) -> i32 {
let mut sum = 0;
for &i in v.iter() {
sum += i;
if i > 0 { v.push(0); }
}
sum
}
Might free
underlying buffer.
11. Safe
6
fn this_wont_compile(v: &mut Vec<i32>) -> i32 {
let mut sum = 0;
for &i in v.iter() {
sum += i;
if i > 0 { v.push(0); }
}
sum
}
error: cannot borrow `*v` as mutable because it is also borrowed
as immutable
if i > 0 { v.push(0); }
^
note: previous borrow of `*v` occurs here; the immutable borrow
prevents subsequent moves or mutable borrows of `*v` until
the borrow ends
for &i in v.iter() {
^
Might free
underlying buffer.
12. fn parallel_qsort(vec: &mut [int]) {
if vec.len() <= 1 { return; }
let pivot = vec[random(vec.len())];
let mid = vec.partition(vec, pivot);
let (less, greater) = vec.split_at_mut(mid);
rayon::join(
|| parallel_qsort(less),
|| parallel_qsort(greater)
);
}
Parallel
7Caveat: shameless plug for third-party package of mine.
13. fn parallel_qsort(vec: &mut [int]) {
if vec.len() <= 1 { return; }
let pivot = vec[random(vec.len())];
let mid = vec.partition(vec, pivot);
let (less, greater) = vec.split_at_mut(mid);
rayon::join(
|| parallel_qsort(less),
|| parallel_qsort(greater)
);
}
Parallel
7
Sort left and right
in parallel.Caveat: shameless plug for third-party package of mine.
14. fn parallel_qsort(vec: &mut [int]) {
if vec.len() <= 1 { return; }
let pivot = vec[random(vec.len())];
let mid = vec.partition(vec, pivot);
let (less, greater) = vec.split_at_mut(mid);
rayon::join(
|| parallel_qsort(less),
|| parallel_qsort(less)
);
}
Parallel… and safe
8
Data race.
15. fn parallel_qsort(vec: &mut [int]) {
if vec.len() <= 1 { return; }
let pivot = vec[random(vec.len())];
let mid = vec.partition(vec, pivot);
let (less, greater) = vec.split_at_mut(mid);
rayon::join(
|| parallel_qsort(less),
|| parallel_qsort(less)
);
}
Parallel… and safe
8
error: closure requires unique access to `less`
but it is already borrowed
|| parallel_qsort(less)
^~~~~~~~~~~~~~~~~~~~~~~
Data race.
16. Open and welcoming
Rust has been open source from the beginning.
!
Open governance model based on public RFCs.
!
We have an active, amazing community.
❤
9
63. Copy (auto-Clone)
19
fn main() {
let name = 22;
helper(name);
helper(name);
}
fn helper(name: i32) {
println!(..);
}
!
!
!
i32 is a Copy type
64. Copy (auto-Clone)
19
fn main() {
let name = 22;
helper(name);
helper(name);
}
fn helper(name: i32) {
println!(..);
}
!
!
!
i32 is a Copy type
65. Copy (auto-Clone)
19
fn main() {
let name = 22;
helper(name);
helper(name);
}
fn helper(name: i32) {
println!(..);
}
!
!
!
i32 is a Copy type
66. Copy (auto-Clone)
19
fn main() {
let name = 22;
helper(name);
helper(name);
}
fn helper(name: i32) {
println!(..);
}
!
!
!
i32 is a Copy type
67. Copy (auto-Clone)
19
fn main() {
let name = 22;
helper(name);
helper(name);
}
fn helper(name: i32) {
println!(..);
}
!
!
!
i32 is a Copy type
68. 20
Non-copyable: Values move from place to place.
Examples: File descriptor, database handle.
!
Clone: Run custom code to make a copy.
Examples: String, Vector!
!
Copy: Type is implicitly copied when referenced.
Examples: u32, i32, (f32, i32).
76. fn helper(name: &String) {
println!(..);
}
!
!
!
fn main() {
let name = format!(“…”);
helper(&name);
helper(&name);
}
Shared borrow
Take a reference
to a String
23
77. fn helper(name: &String) {
println!(..);
}
!
!
!
fn main() {
let name = format!(“…”);
helper(&name);
helper(&name);
}
Shared borrow
Take a reference
to a String
23
Lend the string
78. fn helper(name: &String) {
println!(..);
}
!
!
!
fn main() {
let name = format!(“…”);
helper(&name);
helper(&name);
}
Shared borrow
Take a reference
to a String
23
Lend the string
79. fn helper(name: &String) {
println!(..);
}
!
!
!
fn main() {
let name = format!(“…”);
helper(&name);
helper(&name);
}
Shared borrow
Take a reference
to a String
23
Lend the string
135. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
136. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
137. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
138. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
139. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
140. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
141. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
142. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
143. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
144. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
145. GC vs C++ vs Rust
31
GC’d language (e.g. Java)
One size fits all
`void helper(String name)`
temporary access?
start a thread?
store in a static?
Rust
Temporary references — confined to owner’s scope
Data cannot be freed or mutated while reference is live
C++
No clear rules
Easily invalidated
“Don’t make mistakes”
146. 32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
147. 32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
148. 32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
149. 32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
150. 32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
151. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
152. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
153. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
154. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
155. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
156. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
157. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
158. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
159. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
160. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
Dangling
reference!
161. .capacity: …
.len: 10
name.data ‘R’ ‘u’ … ‘n’ ‘s’
32
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
r
Dangling
reference!
162. fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33http://is.gd/HJyO7A
163. fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33http://is.gd/HJyO7A
164. fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33
Lifetime: span of code where reference is used.
http://is.gd/HJyO7A
165. fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33
Lifetime: span of code where reference is used.
http://is.gd/HJyO7A
166. fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33
Lifetime: span of code where reference is used.
http://is.gd/HJyO7A
167. fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33
Lifetime: span of code where reference is used.
http://is.gd/HJyO7A
168. fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33
Lifetime: span of code where reference is used.
http://is.gd/HJyO7A
169. fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33
Lifetime: span of code where reference is used.
http://is.gd/HJyO7A
170. fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33
‘l
Lifetime: span of code where reference is used.
http://is.gd/HJyO7A
171. fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33
‘l
Lifetime: span of code where reference is used.
Scope of data being borrowed (here, `name`)
compared against
http://is.gd/HJyO7A
172. ‘s
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33
‘l
Lifetime: span of code where reference is used.
Scope of data being borrowed (here, `name`)
compared against
http://is.gd/HJyO7A
173. ‘s
fn main() {
let r;
{
let name = format!(“…”);
r = &name;
}
println!(“{}”, r);
}
33
‘l
Lifetime: span of code where reference is used.
Scope of data being borrowed (here, `name`)
compared against
http://is.gd/HJyO7A
error: `name` does not live long enough
r = &name;
^~~~
178. 34
use std::thread;
!
fn helper(name: &String) {
thread::spawn(move || {
use(name);
});
}
`name` can only be
used within this fn
Might escape
the function!
179. 34
use std::thread;
!
fn helper(name: &String) {
thread::spawn(move || {
use(name);
});
}
`name` can only be
used within this fn
Might escape
the function!
error: the type `[…]` does not fulfill the required lifetime
thread::spawn(move || {
^~~~~~~~~~~~~
note: type must outlive the static lifetime
180. 34
use std::thread;
!
fn helper(name: &String) {
thread::spawn(move || {
use(name);
});
}
`name` can only be
used within this fn
error: the type `[…]` does not fulfill the required lifetime
thread::spawn(move || {
^~~~~~~~~~~~~
note: type must outlive the static lifetime
181. 34
use std::thread;
!
fn helper(name: &String) {
thread::spawn(move || {
use(name);
});
}
`name` can only be
used within this fn
error: the type `[…]` does not fulfill the required lifetime
thread::spawn(move || {
^~~~~~~~~~~~~
note: type must outlive the static lifetime
182. 34
use std::thread;
!
fn helper(name: &String) {
thread::spawn(move || {
use(name);
});
}
`name` can only be
used within this fn
error: the type `[…]` does not fulfill the required lifetime
thread::spawn(move || {
^~~~~~~~~~~~~
note: type must outlive the static lifetime
183. 34
use std::thread;
!
fn helper(name: &String) {
thread::spawn(move || {
use(name);
});
}
`name` can only be
used within this fn
error: the type `[…]` does not fulfill the required lifetime
thread::spawn(move || {
^~~~~~~~~~~~~
note: type must outlive the static lifetime
However: see crossbeam,
simple_parallel, etc on
crates.io
184. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
185. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
186. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
‘R’ ‘u’ … ‘n’
String
data
len
capacity
187. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
‘R’ ‘u’ … ‘n’
String
data
len
capacity
188. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
‘R’ ‘u’ … ‘n’
String
data
len
capacity
189. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
‘R’ ‘u’ … ‘n’
String
data
len
capacity
data
len
190. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
‘R’ ‘u’ … ‘n’
String
data
len
capacity
data
len
191. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
‘R’ ‘u’ … ‘n’
String
data
len
capacity
data
len
192. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
‘R’ ‘u’ … ‘n’
String
data
len
capacity
‘R’ ‘u’ … ‘n’
data
len
193. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
‘R’ ‘u’ … ‘n’
String
data
len
capacity
‘R’ ‘u’ … ‘n’
data
len
‘s’
194. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
String
data
len
capacity
‘R’ ‘u’ … ‘n’
data
len
‘R’ ‘u’ … ‘n’
‘s’
195. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
String
data
len
capacity
‘R’ ‘u’ … ‘n’
data
len
‘R’ ‘u’ … ‘n’
‘s’
196. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
String
data
len
capacity
‘R’ ‘u’ … ‘n’
data
len
‘R’ ‘u’ … ‘n’
‘s’
197. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
String
data
len
capacity
‘R’ ‘u’ … ‘n’
data
len
‘R’ ‘u’ … ‘n’
‘s’
Dangling
reference!
198. Dangers of mutation
35
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
String
data
len
capacity
‘R’ ‘u’ … ‘n’
data
len
‘R’ ‘u’ … ‘n’
‘s’
Dangling
reference!
199. Rust solution
36
Compile-time read-write-lock:!
!
Creating a shared reference to X “read locks” X.
- Other readers OK.
- No writers.
- Lock lasts until reference goes out of scope.
!
Creating a mutable reference to X “writes locks” X.
- No other readers or writers.
- Lock lasts until reference goes out of scope.
Never have a reader/writer at same time.
200. Dangers of mutation
37
fn main() {
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
http://is.gd/MCPVWg
201. Dangers of mutation
37
fn main() {
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
http://is.gd/MCPVWg
202. Dangers of mutation
37
fn main() {
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
Borrow “locks”
`buffer` until `slice`
goes out of scope
http://is.gd/MCPVWg
203. Dangers of mutation
37
fn main() {
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
Borrow “locks”
`buffer` until `slice`
goes out of scope
http://is.gd/MCPVWg
204. Dangers of mutation
37
fn main() {
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
Borrow “locks”
`buffer` until `slice`
goes out of scope
error: cannot borrow `buffer` as mutable
because it is also borrowed as immutable
buffer.push_str(“s”);
^~~~~~
http://is.gd/MCPVWg
205. Dangers of mutation
37
fn main() {
let mut buffer: String = format!(“Rustacean”);
let slice = &buffer[1..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
Borrow “locks”
`buffer` until `slice`
goes out of scope
error: cannot borrow `buffer` as mutable
because it is also borrowed as immutable
buffer.push_str(“s”);
^~~~~~
http://is.gd/MCPVWg
206. fn main() {
let mut buffer: String = format!(“Rustacean”);
for i in 0 .. buffer.len() {
let slice = &buffer[i..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
buffer.push_str(“s”);
}
38
207. fn main() {
let mut buffer: String = format!(“Rustacean”);
for i in 0 .. buffer.len() {
let slice = &buffer[i..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
buffer.push_str(“s”);
}
38
Borrow “locks”
`buffer` until `slice`
goes out of scope
208. fn main() {
let mut buffer: String = format!(“Rustacean”);
for i in 0 .. buffer.len() {
let slice = &buffer[i..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
buffer.push_str(“s”);
}
38
Borrow “locks”
`buffer` until `slice`
goes out of scope
209. fn main() {
let mut buffer: String = format!(“Rustacean”);
for i in 0 .. buffer.len() {
let slice = &buffer[i..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
buffer.push_str(“s”);
}
38
Borrow “locks”
`buffer` until `slice`
goes out of scope
210. fn main() {
let mut buffer: String = format!(“Rustacean”);
for i in 0 .. buffer.len() {
let slice = &buffer[i..];
buffer.push_str(“s”);
println!(“{:?}”, slice);
}
buffer.push_str(“s”);
}
38
Borrow “locks”
`buffer` until `slice`
goes out of scope
OK: `buffer` is not borrowed here
243. Methods
44
struct Store { .. }
struct Item { .. }
!
impl Store {
fn add_item(&mut self, item: Item) {
self.items.push(item);
}
!
fn price(&self, item_name: &str) -> f32 {
… // see upcoming slide
}
}
store.add_item(…); // must be let mut
store.price(…); // let OR let mut
244. Methods
44
struct Store { .. }
struct Item { .. }
!
impl Store {
fn add_item(&mut self, item: Item) {
self.items.push(item);
}
!
fn price(&self, item_name: &str) -> f32 {
… // see upcoming slide
}
}
store.add_item(…); // must be let mut
store.price(…); // let OR let mut
245. Methods
44
struct Store { .. }
struct Item { .. }
!
impl Store {
fn add_item(&mut self, item: Item) {
self.items.push(item);
}
!
fn price(&self, item_name: &str) -> f32 {
… // see upcoming slide
}
}
store.add_item(…); // must be let mut
store.price(…); // let OR let mut
itself an &mut method
246. Methods
44
struct Store { .. }
struct Item { .. }
!
impl Store {
fn add_item(&mut self, item: Item) {
self.items.push(item);
}
!
fn price(&self, item_name: &str) -> f32 {
… // see upcoming slide
}
}
store.add_item(…); // must be let mut
store.price(…); // let OR let mut
247. Methods
44
struct Store { .. }
struct Item { .. }
!
impl Store {
fn add_item(&mut self, item: Item) {
self.items.push(item);
}
!
fn price(&self, item_name: &str) -> f32 {
… // see upcoming slide
}
}
store.add_item(…); // must be let mut
store.price(…); // let OR let mut
248. Methods
44
struct Store { .. }
struct Item { .. }
!
impl Store {
fn add_item(&mut self, item: Item) {
self.items.push(item);
}
!
fn price(&self, item_name: &str) -> f32 {
… // see upcoming slide
}
}
store.add_item(…); // must be let mut
store.price(…); // let OR let mut
249. Methods
44
struct Store { .. }
struct Item { .. }
!
impl Store {
fn add_item(&mut self, item: Item) {
self.items.push(item);
}
!
fn price(&self, item_name: &str) -> f32 {
… // see upcoming slide
}
}
store.add_item(…); // must be let mut
store.price(…); // let OR let mut
250. Methods
44
struct Store { .. }
struct Item { .. }
!
impl Store {
fn add_item(&mut self, item: Item) {
self.items.push(item);
}
!
fn price(&self, item_name: &str) -> f32 {
… // see upcoming slide
}
}
store.add_item(…); // must be let mut
store.price(…); // let OR let mut
251. Methods
44
struct Store { .. }
struct Item { .. }
!
impl Store {
fn add_item(&mut self, item: Item) {
self.items.push(item);
}
!
fn price(&self, item_name: &str) -> f32 {
… // see upcoming slide
}
}
store.add_item(…); // must be let mut
store.price(…); // let OR let mut
252. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
253. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
254. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
Store::new(some_name)
255. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
Store::new(some_name)
256. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
Store::new(some_name)
257. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
Store::new(some_name)
258. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
Store::new(some_name)
259. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
Store::new(some_name)
260. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
Store::new(some_name)
261. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
Store::new(some_name)
262. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
Store::new(some_name)
263. Methods
45
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
return Store {
name: name,
items: vec![],
};
}
}
Store::new(some_name)
264. Return is optional
46
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
Store {
name: name,
items: vec![],
}
}
}
265. Return is optional
46
struct Store { .. }
!
impl Store {
fn new(name: String) -> Store {
Store {
name: name,
items: vec![],
}
}
}
No `;` on last expression:
“return this value”
277. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Alpha”
“Beta”
“Gamma”
v: s:
278. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Alpha”
“Beta”
“Gamma”
v: s:
279. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Alpha”
“Beta”
“Gamma”
v: s:
280. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Alpha”
“Beta”
“Gamma”
v: s:
281. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Alpha”
“Beta”
“Gamma”
v: s:
Vec<String>
282. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Alpha”
“Beta”
“Gamma”
v: s:
String
Vec<String>
283. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Alpha”
“Beta”
“Gamma”
v: s:
284. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Alpha”
“Beta”
“Gamma”
v: s:
285. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Beta”
“Gamma”
v: s:
286. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Beta”
“Gamma”
v: s:
287. For Loops
48
fn main() {
let v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
for s in v {
println!(“{:?}”, s);
}
}
http://is.gd/6kJc0O
“Gamma”
v: s:
288. For Loops
49
fn main() {
let mut v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
!
for s in &v {
println!(“{:?}”, s);
}
!
for s in &mut v {
s.push_str(“.”);
}
}
“Alpha”
“Beta”
“Gamma”
v:
289. For Loops
49
fn main() {
let mut v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
!
for s in &v {
println!(“{:?}”, s);
}
!
for s in &mut v {
s.push_str(“.”);
}
}
“Alpha”
“Beta”
“Gamma”
v:
290. For Loops
49
fn main() {
let mut v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
!
for s in &v {
println!(“{:?}”, s);
}
!
for s in &mut v {
s.push_str(“.”);
}
}
“Alpha”
“Beta”
“Gamma”
v:
&Vec<String>
291. For Loops
49
fn main() {
let mut v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
!
for s in &v {
println!(“{:?}”, s);
}
!
for s in &mut v {
s.push_str(“.”);
}
}
“Alpha”
“Beta”
“Gamma”
v:
&String
&Vec<String>
292. For Loops
49
fn main() {
let mut v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
!
for s in &v {
println!(“{:?}”, s);
}
!
for s in &mut v {
s.push_str(“.”);
}
}
“Alpha”
“Beta”
“Gamma”
v:
293. For Loops
49
fn main() {
let mut v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
!
for s in &v {
println!(“{:?}”, s);
}
!
for s in &mut v {
s.push_str(“.”);
}
}
“Alpha”
“Beta”
“Gamma”
v:
s:
294. For Loops
49
fn main() {
let mut v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
!
for s in &v {
println!(“{:?}”, s);
}
!
for s in &mut v {
s.push_str(“.”);
}
}
“Alpha”
“Beta”
“Gamma”
v:
s:
295. For Loops
49
fn main() {
let mut v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
!
for s in &v {
println!(“{:?}”, s);
}
!
for s in &mut v {
s.push_str(“.”);
}
}
“Alpha”
“Beta”
“Gamma”
v:
s:
296. For Loops
49
fn main() {
let mut v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
!
for s in &v {
println!(“{:?}”, s);
}
!
for s in &mut v {
s.push_str(“.”);
}
}
“Alpha”
“Beta”
“Gamma”
v:
s:
&mut Vec<String>
&mut String
297. For Loops
49
fn main() {
let mut v = vec![format!(“Alpha”),
format!(“Beta”),
format!(“Gamma”)];
!
for s in &v {
println!(“{:?}”, s);
}
!
for s in &mut v {
s.push_str(“.”);
}
}
“Alpha”
“Beta”
“Gamma”
v:
s:
308. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
309. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
310. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
311. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
312. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
313. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
314. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
315. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
316. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
317. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
318. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
319. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
320. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
321. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
322. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
323. 54
let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
324. let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
55
325. let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
55
326. let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
55
327. let mut best = None;
let mut best_price = INFINITY;
for store in stores {
let sum = store.total_price(&shopping_list);
match sum {
Some(s) if s < best_price => {
best = Some(store.name);
best_price = s;
}
_ => { }
}
}
55
328. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
329. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
330. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
331. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
332. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
333. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
334. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
335. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
Closure
takes ownership
of variables it uses.
336. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
Closure
takes ownership
of variables it uses.
Variables used by
this closure.
337. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
Closure
takes ownership
of variables it uses.
Variables used by
this closure.
338. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
339. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
Handle to the
thread we spawned.
340. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
341. Closure body can
produce a result,
here a (String, f32).
use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
342. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
343. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
344. use std::thread;
…
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
56
347. 57
let handle = thread::spawn(…);
… // stuff in parallel
// with new thread
348. 57
let handle = thread::spawn(…);
… // stuff in parallel
// with new thread
let (name, sum) = handle.join().unwrap();
349. 57
let handle = thread::spawn(…);
… // stuff in parallel
// with new thread
let (name, sum) = handle.join().unwrap();
350. 57
let handle = thread::spawn(…);
… // stuff in parallel
// with new thread
let (name, sum) = handle.join().unwrap();
Wait for thread
to finish and
get return value.
351. 57
let handle = thread::spawn(…);
… // stuff in parallel
// with new thread
let (name, sum) = handle.join().unwrap();
Wait for thread
to finish and
get return value.
Result<(String, f32), Error>
352. 57
let handle = thread::spawn(…);
… // stuff in parallel
// with new thread
let (name, sum) = handle.join().unwrap();
Wait for thread
to finish and
get return value.
Thread may have
panicked. Propagate.
353. 57
let handle = thread::spawn(…);
… // stuff in parallel
// with new thread
let (name, sum) = handle.join().unwrap();
Wait for thread
to finish and
get return value.
Thread may have
panicked. Propagate.Result of thread.
354. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
355. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
356. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
357. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
358. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
359. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
360. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
361. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
362. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
363. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
364. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
365. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
366. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
367. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
368. 58
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
handles.push(
thread::spawn(move || {
let sum = …;
(store.name, sum)
});
}
!
for handle in handles {
let (name, sum) =
handle.join().unwrap();
// find best price
}
369. 59
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
370. 59
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
Variables used by
this closure.
371. 59
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
372. 59
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
373. 59
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
374. 59
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
375. 59
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
error: capture of moved value: `shopping_list`
let sum = store.total_price(&shopping_list);
^~~~~~~~~~~~~
…
help: perhaps you meant to use `clone()`?
376. 59
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
error: capture of moved value: `shopping_list`
let sum = store.total_price(&shopping_list);
^~~~~~~~~~~~~
…
help: perhaps you meant to use `clone()`?
377. 60
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
378. 60
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
379. 60
use std::thread;
…
let shopping_list = vec![…];
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
400. Arc => Immutable
62
use std::sync::Arc;
let shopping_list: Vec<ShoppingList> = …;
let arc1 = Arc::new(shopping_list);
let data = &mut arc1[0];
http://is.gd/nP3Pvb
401. Arc => Immutable
62
use std::sync::Arc;
let shopping_list: Vec<ShoppingList> = …;
let arc1 = Arc::new(shopping_list);
let data = &mut arc1[0];
http://is.gd/nP3Pvb
402. Arc => Immutable
62
use std::sync::Arc;
let shopping_list: Vec<ShoppingList> = …;
let arc1 = Arc::new(shopping_list);
let data = &mut arc1[0];
<anon>:6:21: 6:24 error: cannot borrow immutable borrowed
content as mutable
<anon>:6 let data = &mut arc[0];
^~~
http://is.gd/nP3Pvb
403. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
404. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
405. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
406. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
407. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
408. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
409. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
410. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
411. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
412. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
413. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
414. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
415. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
416. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
417. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
418. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
419. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
420. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
421. 63
use std::thread;
…
let shopping_list = Arc::new(vec![…]);
let mut handles = vec![];
for store in stores {
let shopping_list = shopping_list.clone();
let handle =
thread::spawn(move || {
let sum = store.total_price(shopping_list);
(store.name, sum)
});
handles.push(handle);
}
// exercise (in a bit): join the handles!