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 :)
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.
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
Rust is a young programming language developed by Mozilla with the open source community support. According to a survey of StackOverflow, in 2016 was the most loved among developers language! The goal of Rust is to combine control and performances, that is, operate at low level with high-level constructs. The actual applications vary from operating system to web development. Rust natively includes tools for Agile development, such as dependency management, testing and much more. The gap with other popular languages is filling up quickly thanks to the community, very active and fantastic :)
In this introductory presentation we will discuss the characteristics that make Rust unique, including the concepts of Ownership, Borrowing, and Lifetimes.
These slide has be presented for a talk in BIC Lazio Casilina, that has been also the first meetup of Rust Rome!
Brief overview of the Rust system programming language. Provides a concise introduction of its basic features, with an emphasis on its memory safety features (ownership, moves, borrowing) and programming style with generic functions, structures, and traits.
Rust has something unique to offer that languages in that space have never had before, and that is a degree of safety that languages like C and C++ have never had. Rust promises to deliver equivalent or better performance and greater productivity with guaranteed memory safety and data race freedom while allowing complete and direct control over memory.
This video will cover:
What is Rust?
Benefits of Rust
Rust Ecosystem
Popular Applications in Rust
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.
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
Rust is a young programming language developed by Mozilla with the open source community support. According to a survey of StackOverflow, in 2016 was the most loved among developers language! The goal of Rust is to combine control and performances, that is, operate at low level with high-level constructs. The actual applications vary from operating system to web development. Rust natively includes tools for Agile development, such as dependency management, testing and much more. The gap with other popular languages is filling up quickly thanks to the community, very active and fantastic :)
In this introductory presentation we will discuss the characteristics that make Rust unique, including the concepts of Ownership, Borrowing, and Lifetimes.
These slide has be presented for a talk in BIC Lazio Casilina, that has been also the first meetup of Rust Rome!
Brief overview of the Rust system programming language. Provides a concise introduction of its basic features, with an emphasis on its memory safety features (ownership, moves, borrowing) and programming style with generic functions, structures, and traits.
Rust has something unique to offer that languages in that space have never had before, and that is a degree of safety that languages like C and C++ have never had. Rust promises to deliver equivalent or better performance and greater productivity with guaranteed memory safety and data race freedom while allowing complete and direct control over memory.
This video will cover:
What is Rust?
Benefits of Rust
Rust Ecosystem
Popular Applications in Rust
Rust is the new kid on the block. It's a system programming language that is blazingly fast and offers powerful high-level abstractions better known from dynamic languages like Ruby or Python. Rust offers memory safety without a Garbage Collector and makes low-level programming easier and more secure. I will give an introductory talk about Rust and show some of its nicest features.
A basic Introduction to Rust. Rust is a modern system programming language which offering different approach than other existing new modern system programming languages to deal with: memory safety without GC, abstraction without overhead, and concurrency without data races.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/28XnVtb.
Felix Klock describe the core concepts of the Rust language (ownership, borrowing, and lifetimes), as well as the tools beyond the compiler for open source software component distribution (cargo, crates.io). Filmed at qconlondon.com.
Felix Klock is a research engineer at Mozilla, where he works on the Rust compiler, runtime libraries, and language design. He previously worked on the ActionScript Virtual Machine for the Adobe Flash runtime. Klock is one of the developers of the Larceny Scheme language runtime.
Rust is a multi-paradigm systems programming language focused on safety, especially safe concurrency. Rust is syntactically similar to C++, but is designed to provide better memory safety while maintaining high performance.
This talk covers the following: principles of design, features, and applications. There are many successful projects used Rust, including browsers, operation systems, and database management systems, which will be also discussed in the talk.
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.
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...Edureka!
( ** Edureka Online Training: https://www.edureka.co/ ** )
This video on Rust Programming Language will help you understand basics of Rust programming. The following topics will be covered in this tutorial:
1. Why learn Rust?
2. What is Rust?
3. Install Rust
4. Rust Fundamentals
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
LXC, Docker, security: is it safe to run applications in Linux Containers?Jérôme Petazzoni
Linux Containers (or LXC) is now a popular choice for development and testing environments. As more and more people use them in production deployments, they face a common question: are Linux Containers secure enough? It is often claimed that containers have weaker isolation than virtual machines. We will explore whether this is true, if it matters, and what can be done about it.
A talk I gave at the Golang TO Meetup. Highlighting the beautiful powers of Go with respect to concurrency, and writing concurrent programs using it.
Code at: github.com/jsimnz/concurrency-talk
Introduction to GoLang by Amal Mohan N. This presentation is an introduction to GoLang - it's history, features, syntax, importance etc.
concurrency, go-routines, golang, google, gopher, introduction, programming
Доклад рассказывает об устройстве и опыте применения инструментов динамического тестирования C/C++ программ — AddressSanitizer, ThreadSanitizer и MemorySanitizer. Инструменты находят такие ошибки, как использование памяти после освобождения, обращения за границы массивов и объектов, гонки в многопоточных программах и использования неинициализированной памяти.
Back in 2015, Square and Google collaborated to launch gRPC, an open source RPC framework backed by protocol buffers and HTTP/2, based on real-world experiences operating microservices at scale. If you build microservices, you will be interested in gRPC.
This webcast covers:
- a technical overview of gRPC
- use cases and applicability in your stack
- a deep dive into the practicalities of operationalizing gRPC
Rust is the new kid on the block. It's a system programming language that is blazingly fast and offers powerful high-level abstractions better known from dynamic languages like Ruby or Python. Rust offers memory safety without a Garbage Collector and makes low-level programming easier and more secure. I will give an introductory talk about Rust and show some of its nicest features.
A basic Introduction to Rust. Rust is a modern system programming language which offering different approach than other existing new modern system programming languages to deal with: memory safety without GC, abstraction without overhead, and concurrency without data races.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/28XnVtb.
Felix Klock describe the core concepts of the Rust language (ownership, borrowing, and lifetimes), as well as the tools beyond the compiler for open source software component distribution (cargo, crates.io). Filmed at qconlondon.com.
Felix Klock is a research engineer at Mozilla, where he works on the Rust compiler, runtime libraries, and language design. He previously worked on the ActionScript Virtual Machine for the Adobe Flash runtime. Klock is one of the developers of the Larceny Scheme language runtime.
Rust is a multi-paradigm systems programming language focused on safety, especially safe concurrency. Rust is syntactically similar to C++, but is designed to provide better memory safety while maintaining high performance.
This talk covers the following: principles of design, features, and applications. There are many successful projects used Rust, including browsers, operation systems, and database management systems, which will be also discussed in the talk.
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.
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...Edureka!
( ** Edureka Online Training: https://www.edureka.co/ ** )
This video on Rust Programming Language will help you understand basics of Rust programming. The following topics will be covered in this tutorial:
1. Why learn Rust?
2. What is Rust?
3. Install Rust
4. Rust Fundamentals
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
LXC, Docker, security: is it safe to run applications in Linux Containers?Jérôme Petazzoni
Linux Containers (or LXC) is now a popular choice for development and testing environments. As more and more people use them in production deployments, they face a common question: are Linux Containers secure enough? It is often claimed that containers have weaker isolation than virtual machines. We will explore whether this is true, if it matters, and what can be done about it.
A talk I gave at the Golang TO Meetup. Highlighting the beautiful powers of Go with respect to concurrency, and writing concurrent programs using it.
Code at: github.com/jsimnz/concurrency-talk
Introduction to GoLang by Amal Mohan N. This presentation is an introduction to GoLang - it's history, features, syntax, importance etc.
concurrency, go-routines, golang, google, gopher, introduction, programming
Доклад рассказывает об устройстве и опыте применения инструментов динамического тестирования C/C++ программ — AddressSanitizer, ThreadSanitizer и MemorySanitizer. Инструменты находят такие ошибки, как использование памяти после освобождения, обращения за границы массивов и объектов, гонки в многопоточных программах и использования неинициализированной памяти.
Back in 2015, Square and Google collaborated to launch gRPC, an open source RPC framework backed by protocol buffers and HTTP/2, based on real-world experiences operating microservices at scale. If you build microservices, you will be interested in gRPC.
This webcast covers:
- a technical overview of gRPC
- use cases and applicability in your stack
- a deep dive into the practicalities of operationalizing gRPC
This talk exposes the reasons what Servo is and why it is necessary, its current status, future plans and details on the Rust programming language, which has a symbiotic relationship with Servo.
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.
Write a C++ program 1. Study the function process_text() in file.pdfjillisacebi75827
Write a C++ program
1. Study the function process_text() in file \"text_processing.cpp\". What do the string member
functions find(), substr(), c_str() do?
//text_processing.cpp
#include \"util.h\"
#include \"text_processing.h\"
#include
using namespace std;
int process_text( fstream &ifs, fstream &ofs, char target[] )
{
string replace_str( \"XXX\" ); //hard-coded string for replacement
int tlen = strlen( target ); //string length of target
int max_len = 200; //maximum length of a line
char s[max_len+1];
clear_screen(); //clear the screen
while ( !ifs.eof() ) {
int i2, i1 = 0, len=0;
ifs.getline( s, max_len ); //get one line from file
string str( s ); //construct a string object
i2 = str.find ( target, i1 ); //find target
len = i2 - i1;
if ( i2 > -1 && len > 0 ){ //if target found
print_text( str.substr( i1, i2 ).c_str() ); //print up to target
ofs << str.substr( i1, i2 );
}
while ( i2 > -1 ) {
print_text_inverse ( target ); //highlight target
ofs << replace_str;
i1 = i2 + tlen; //new search position
i2 = str.find ( target, i1 ); //find next target
len = i2 - i1;
if ( i2 > -1 && len > 0 ){ //found target
print_text( str.substr( i1, len ).c_str() ); //print up to target
ofs << str.substr( i1, len );
}
}
len = str.length() - i1;
if ( len > 0 ) { //print the remainder
print_text( str.substr( i1, len ).c_str() );
ofs << str.substr( i1, len );
}
ofs << endl;
getnstr( s, 1 ); //prompt for
} //while ( !ifs.eof() )
restore_screen(); //restore the old screen
return 1;
}
//text_processing.h
#ifndef TEXT_PROCESSING_H
#define TEXT_PROCESSING_H
#include
#include
using namespace std;
int process_text( fstream &ifs, fstream &ofs, char target[] );
#endif
//util.h
#ifndef UTIL_H
#define UTIL_H
#include
#include
#include
#include
#include
using namespace std;
void usage ( char program_name[] );
void clear_screen();
void print_text( const char *s );
void print_text_inverse( const char *s );
void get_input_text( char *s, int max_len );
void restore_screen();
#endif
//util.cpp
#include \"util.h\"
void usage ( char program_name[] )
{
cout << \"Usage: \" << program_name << \" infile outfile search_string\" << endl;
return;
}
/*
The following are some curses functions. You can find
the details by the command \"man ncurses\". But its use
can be transparent to you.
*/
void clear_screen()
{
initscr();
scrollok ( stdscr, true ); //allow window to scroll
}
void print_text ( const char *s )
{
printw(\"%s\", s );
refresh();
}
void print_text_inverse( const char *s )
{
attron( A_REVERSE );
printw(\"%s\", s );
attroff( A_REVERSE );
refresh();
}
void get_input_text( char *s, int max_len )
{
getnstr( s, max_len );
}
void restore_screen()
{
endwin();
}
//str_main.cpp
#include \"util.h\"
#include \"text_processing.h\"
#include
using namespace std;
/*
Note that grace_open() must be defined in same file
as main(), otherwise the destructor of fstream will
automatically close the opened file as it finds that
its out of scope upon exiting the function.
*/
int grace_open( char *s, fst.
An introduction into Googles programming language Go, which had its first release in March 2012. The talk has been held at the regulars' table of the GTUG Bremen.
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
An overview of some of the history of JavaScript, how it became ECMAScript (and what Ecma is), as well as highlights of the new features and syntax in ES6 aka ES2015.
Originally presented to the New York Public Library on June 4 2015.
Program Assignment Process ManagementObjective This program a.docxwkyra78
Program Assignment : Process Management
Objective: This program assignment is given to the Operating Systems course to allow the students to figure out how a single process (parent process) creates a child process and how they work on Unix/Linux(/Mac OS X/Windows) environment. Additionally, student should combine the code for describing inter-process communication into this assignment. Both parent and child processes interact with each other through shared memory-based communication scheme or message passing scheme.
Environment: Unix/Linux environment (VM Linux or Triton Server, or Mac OS X), Windows platform
Language: C or C++, Java
Requirements:
i. You have wide range of choices for this assignment. First, design your program to explain the basic concept of the process management in Unix Kernel. This main idea will be evolved to show your understanding on inter-process communication, file processing, etc.
ii. Refer to the following system calls:
- fork(), getpid(), family of exec(), wait(), sleep() system calls for process management
- shmget(), shmat(), shmdt(), shmctl() for shared memory support or
- msgget(), msgsnd(), msgrcv(), msgctl(), etc. for message passing support
iii. The program should present that two different processes, both parent and child, execute as they are supposed to.
iv. The output should contain the screen capture of the execution procedure of the program.
v. Interaction between parent and child processes can be provided through inter-process communication schemes, such as shared-memory or message passing schemes.
vi. Result should be organized as a document which explains the overview of your program, code, execution results, and the conclusion including justification of your program, lessons you've learned, comments, etc.
Note:
i. In addition, please try to understand how the local and global variables work across the processes
ii. read() or write () functions are used to understand how they work on the different processes.
iii. For extra credit, you can also incorporate advanced features, like socket or thread functions, into your code.
Examples:
1. Process Creation and IPC with Shared Memory Scheme
=============================================================
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
pid_t pid;
int segment_id; //allocate the memory
char *shared_memory; //pointer to memory
const int size = 4096;
segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR);
shared_memory = (char *) shmat(segment_id, NULL, 0);
pid = fork();
if(pid < 0) { //error
fprintf(stderr, "Fork failed");
return 1;
}
else if(pid == 0){ //child process
char *child_shared_memory;
child_shared_memory = (char *) shmat(segment_id,NULL,0); //attach mem
sprintf(child_shared_memory, "Hello parent process!"); //write to the shared mem
shmdt(child_shared_memory);
}
else ...
A discussion on the upcoming new features in ES6 and how they change the way we build applications with JavaScript.
Most Notable Upcoming Changes in EcmaScript 6
Classes: Classes are now first-class citizens in ES6. The language offers support for classes ("class" keyword), constructors ("constructor" keyword) and the "extend" keyword for inheritance.
Modules: Modules provide a much needed way to segment and organize JavaScript applications in logical chunks of code. Many frameworks already provide ways to modularize large apps, but standardizing a common module structure will bring a level of interoperability between various JavaScript libraries.
Block Scoping: Scoping in JavaScript can be a confusing topic for programmers coming from more traditional Object-Oriented languages such as Java or C#. There are basically two scopes in JavaScript: global and function. Until now. With the help of the "let" keyword, ES6 enables the definition of block scopes for variables and functions.
Default Parameters: A liked feature of many other languages such as Ruby, the default parameters save endless checking of they've been passed and if they are "undefined".
Enhanced Object Literals: There is now a handy expression for property: property assignments and methods can be defined without the "function" keyword.
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
••• Exploit the full potential of the CRTP! •••
In this presentation you will learn:
▸ what is the curiously recurring template pattern
▸ the actual cost (memory and time) of virtual functions
▸ how to implement static polymorphism
▸ how to implement expression templates to avoid loops and copies
A brief look at the new features coming in Javascript ES6:
- Scope and control
- Iterators and Generators
- Collections
- Typed objects
- Direct proxies
- Template strings
- API improvements
- Modularity
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
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
CFD analysis is incredibly effective at solving mysteries and improving the performance of complex systems!
Here's a great example: At a large natural gas-fired power plant, where they use waste heat to generate steam and energy, they were puzzled that their boiler wasn't producing as much steam as expected.
R&R and Tetra Engineering Group Inc. were asked to solve the issue with reduced steam production.
An inspection had shown that a significant amount of hot flue gas was bypassing the boiler tubes, where the heat was supposed to be transferred.
R&R Consult conducted a CFD analysis, which revealed that 6.3% of the flue gas was bypassing the boiler tubes without transferring heat. The analysis also showed that the flue gas was instead being directed along the sides of the boiler and between the modules that were supposed to capture the heat. This was the cause of the reduced performance.
Based on our results, Tetra Engineering installed covering plates to reduce the bypass flow. This improved the boiler's performance and increased electricity production.
It is always satisfying when we can help solve complex challenges like this. Do your systems also need a check-up or optimization? Give us a call!
Work done in cooperation with James Malloy and David Moelling from Tetra Engineering.
More examples of our work https://www.r-r-consult.dk/en/cases-en/
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
12. Using cargo to create projects
Rust's package manager
Usage:
cargo <command> [<args>...]
cargo [options]
Options:
-h, --help Display this message
-V, --version Print version info and exit
--list List installed commands
-v, --verbose Use verbose output
Some common cargo commands are:
build Compile the current project
clean Remove the target directory
doc Build this project's and its dependencies' documentation
new Create a new cargo project
run Build and execute src/main.rs
test Run the tests
bench Run the benchmarks
update Update dependencies listed in Cargo.lock
14. primatives
fn main() {
//integers
let i: i8 = 1; // i16, i32, i64, and i are available
//unsigned
let u: u8 = 2; // u16, u32, u64, and u are available
//floats
let f: f32 = 1.0; // f64 also available
//booleans
let b: bool = true; // false also available, duh
//string and characters
let c: char = 'a';
let s: &str = "hello world";
}
15. variable bindings
fn main() {
let x: int = 1; //explicitly declare type
let y = 2i; //type inference
let (a,b,c) = (1i,2i,3i); //variable declaration via patterns
let a = [1, 2, 3]; //array literals
let s = "hello"; //string literal
println!("*_^ x = {}, y = {}, a,b,c = {},{},{}", x,y,a,b,c);
}
//> Cargo run
//> *_^ x = 1, y = 2, a,b,c = 1,2,3
//
16. variable mutability
fn main() {
let x: int = 1;
x = 10;
println!("The value of x is {}", x);
}
//Cargo run
//error: re-assignment of immutable variable `x`
// x = 10;
// ^~~~~~~
17. variable mutability
fn main() {
let mut x: int = 1;
x = 10;
println!("The value of x is {}", x);
}
//Cargo run
//warning: value assigned to `x` is never read
// let mut x: int = 1;
// ^~~~~~~
18. The Rust compiler is SUPER helpful
fn main() {
let mut x: int = 1;
x = 10;
println!("The value of x is {}", x);
}
//Cargo run
//warning: value assigned to `x` is never read
// let mut x: int = 1;
// ^~~~~~~
19. stack vs. heap
fn main() {
let y: int = 1; //allocated on the stack
let x: Box<int> = Box::new(10); //allocated on the heap
println!("Heap {}, Stack {}", x, y);
}
//> Cargo run
//> Heap 10, Stack 1
//
20. heap allocation creates pointers
fn main() {
let x: Box<int> = box 10; //allocated on the heap
x = 11;
println!("The Heaps new value is {}, x");
}
//Cargo run
//error: mismatched types: expected `Box<int>`
// x = 11;
// ^~~~~~~
21. memory mutability
fn main() {
let x: Box<int> = box 10; //allocated on the heap
*x = 11;
println!("The Heaps new value is {}, x");
}
//Cargo run
//error: cannot assign to immutable dereference of `*x`
// x = 11;
// ^~~~~~~
22. memory mutability
fn main() {
let mut x: Box<int> = box 10; //allocated on the heap
*x = 11;
println!("The Heaps new value is {}, x");
}
//> Cargo run
//> The Heaps new value is 11
//
23. compiler protects you by owning de-allocation
fn main() {
let mut x: Box<int> = box::new(10); //allocated on the heap
*x = 11;
println!("The Heaps new value is {}, x");
//Scope for x ends here so the compiler adds the de-allocation
//free(x);
}
//> Cargo run
//> The Heaps new value is 11
//
24. There is no garbage
collection in Rust. The
compiler observes the
lifetime of a variable and
de-allocates it where it is
no longer used.
26. borrowing
fn main() {
// x is the owner of the integer, which is memory on the stack.
let x = 5;
// you may lend that resource to as many borrowers as you like
let y = &x;
let z = &x;
// functions can borrow too!
foo(&x);
// we can do this alllllll day!
let a = &x;
}
27. ownership is singular
fn main() {
let mut x = 5;
let y = &mut x; //mutability only allows one borrower
let z = &mut x; // ... no go
}
//> Cargo build
//> error: cannot borrow `x` as mutable more than once at a time
// let z = &mut x;
// ^~~~~~~~~~~~~~~
28. ownership can be transferred
fn main() {
let x: Box<i32> = Box::new(5);
let y = add_one(x);
println!("{}", y);
}
fn add_one(mut num: Box<i32>) -> Box<i32> {
*num += 1;
num
}
//> Cargo run
//> 6
//
29. ownership can be transferred back
fn main() {
let mut x: Box<i32> = Box::new(5);
x = add_one(x);
println!("{}", x);
}
fn add_one(mut num: Box<i32>) -> Box<i32> {
*num += 1;
num
}
//> Cargo run
//> 6
//
30. now THAT sums to to the
promised memory safety
and data race prevention
32. pattern matching
fn main() {
let x = 5;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
4 => println!("four"),
5 => println!("five"),
_ => println!("something else"),
}
}
33. pattern matching
fn main() {
let x = 5;
match x {
1 | 2 => println!("one or two"),
3 => println!("three"),
4 ... 7 => println!("4 through 7"),
_ => println!("anything"),
}
}
34. pattern matching
fn main(){
struct Point {
x: i32,
y: i32,
}
let origin = Point { x: 0, y: 0 };
match origin {
Point { x: x, .. } => println!("x is {}", x),
}
}
//> Cargo run
//> x is 0
//
35. iterators & adapters
fn main(){
for i in range(1i, 10i).filter(|&x| x % 2 == 0) {
println!("{}", i);
}
}
//> Cargo run
//> 2
//> 4
//> 6
//> 8
36. functions
//a function that takes and integer and returns an integer
fn add_one(x: i32) -> i32 {
x + 1
}
fn main(){
println!("1 plus 1 is {}", add_one(1));
}
//> Cargo run
//> 1 plus 1 is 2
//
37. closures
fn main() {
let add_one = |x| { 1 + x };
println!("The sum of 5 plus 1 is {}.", add_one(5));
}
//> Cargo run
//> The sum of 5 plus 1 is 6.
//
38. closures can be passed as params
//Generic function that takes a closure as an argument
fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 {
f(x) + f(x)
}
fn main() {
let result = twice(5, |x: i32| { x * x });
println!("And we have .... {}", result);
}
//> Cargo run
//> And we have .... 50
//
39. traits
struct Circle {
x: f64,
y: f64,
radius: f64,
}
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
fn main() {
let c = Circle {x:0.0, y:1.0, radius: 2.0};
println!("The circles's radious is {}", c.area());
}
40. traits with generics
trait HasArea {
fn area(&self) -> f64;
}
fn print_area<T: HasArea>(shape: T) {
println!("This shape has an area of {}", shape.area());
}
fn main() {
let c = Circle {x:0.0, y:1.0, radius: 2.0};
print_area(c);
}
//> Cargo run
//> This shape has an area of 12.566371
//
43. concurrency and ownership
fn print_message(){
println!("Hello from within a thread!");
}
fn main() {
let x: int = 5;
spawn(move || print_message);
x = 10;
}
//> Cargo run
//> error: re-assignment of immutable variable `x`
// x = 10;
// ^~~~~~~
47. testing an expected failure
#[test]
#[should_fail]
fn adding_one(){
let expected: int = 5;
let actual: int = 4;
assert_eq!(expected,actual);
}
//> Cargo Test
//> running 1 tests
//> test adding_one ... OK
//
48. making it pass
#[test]
fn adding_one(){
let expected: int = 5;
let actual: int = 5;
assert_eq!(expected,actual);
}
//> Cargo Test
//> running 1 tests
//> test adding_one ... OK
//
49. benchmark tests
#[bench]
fn bench_add_two(b: &mut Bencher) {
let add_one = |x| { 1 + x };
b.iter(|| add_one(2));
}
//> Cargo Test
//> running 1 tests
//> test tests::bench_add_two ... bench: 1 ns/iter (+/- 0)
//> test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured
//
50. As promised Rust
1. guarantees memory safety
2. threads without dataraces
3. zero-cost abstractions (done at compile time)
4. trait-based generics
5. pattern matching
6. type inference
7. & more