\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{seannarr} \pdfinfo{ /Title (draft-rust-book-notes-not-a.pdf) /Creator (Cheatography) /Author (seannarr) /Subject (Draft - Rust Book Notes - Not a Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{591919} \definecolor{LightBackground}{HTML}{F9F7F7} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Draft - Rust Book Notes - Not a Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{seannarr} via \textcolor{DarkBackground}{\uline{cheatography.com/61019/cs/15819/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}seannarr \\ \uline{cheatography.com/seannarr} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Published 25th May, 2018.\\ Updated 26th May, 2018.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{3} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Installation}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{curl https://sh.rustup.rs -sSf | sh \newline export \seqsplit{PATH="\$HOME/.cargo/bin:\$PATH"}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.88666 cm} x{2.09034 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Hello World}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{`fn main() \{ println!("Hello, world!"); \}`} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} compile: rustc main.rs & prinln! = macro! \tn % Row Count 2 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} p{0.4977 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{create variables with let}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{`let foo =5;` // immutable (default)} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{`let mut foo=5;` //mutable} \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{`let foo=5;` ` let foo="hello";` Shadowing allows reuse of variable. useful in type conversions} \tn % Row Count 4 (+ 2) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{`'let foo: u32 =5;` //annotating with type using :} \tn % Row Count 5 (+ 1) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{`let foo=5; foo = 6;` error{[}E0384{]}: cannot assign twice to immutable variable `foo`} \tn % Row Count 7 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{const}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const MAX\_POINTS: u32 = 100\_000; \newline // no mut allowed on const. \newline // it should be annotated with datatype. \newline // It is visible with in the scope it's declared. \newline // only constant expression assignment.. not return value from function or expression evaluated at runtime} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Prelude}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{Rust inserts \newline % Row Count 1 (+ 1) `extern crate std;` \newline % Row Count 2 (+ 1) into the crate root of every crate, and \newline % Row Count 3 (+ 1) `use std::prelude::v1::*;` \newline % Row Count 4 (+ 1) into every module. \newline % Row Count 5 (+ 1) `std::prelude::v1`% Row Count 6 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Prelude is set of types Rust imports.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Import external crate (library)}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{extern crate rand; //external dependency \newline use rand::Rng; //bring Rng trait which defines the methods into scope \newline \newline those in prelude, need not to extern the crate. \newline just use std::io; //brings io trait into scope} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{\&mut and stdin() and io::Result}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{io::stdin() // stdin() = std::io::Stdin instance a handle to standard input \newline .read\_line(\&mut guess) // \&mut - pass by reference and make it mutable \newline .expect("Failed to read line") // io::Result -\textgreater{} If returns Err, it crashes displaying the message} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{io::Result -\textgreater{} Result, Enumerations Ok, Err. If ok, returns the value, if Err, it crashes program. Without expect, compiler warning - Unused io::Result which must be used.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.89126 cm} x{3.08574 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Floating-Point Types}} \tn % Row 0 \SetRowColor{LightBackground} f32 single precision & f64 - double precision (default) \tn % Row Count 2 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} p{0.4977 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Math Operators}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{+, -, *, /} \tn % Row Count 1 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} p{0.4977 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{bool}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{true, false} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{`let t = true; let f: bool = false;`} \tn % Row Count 2 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} p{0.4977 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Character Type}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{`let c='z'; let k: char = 'a';`} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{char is a unicode scalar value.} \tn % Row Count 2 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} p{0.4977 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Tuple Type}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{`let x:(u32,f64,u8) = (6,3.2,1); x.0 =\textgreater{} 6, x.1 =\textgreater{}3.2`} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{destructuring - `let (a,b,c) =x;` a=\textgreater{} 6} \tn % Row Count 3 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{first index in tuple is 0. ex: x.0 =\textgreater{} 6} \tn % Row Count 4 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Array Types}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Fixed Size vs Vector's size can change} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{let a ={[}1,2,3,4{]}} \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Elements of same type} \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{access by index: a{[}0{]}, a{[}1{]}} \tn % Row Count 4 (+ 1) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Invalid Access a{[}10{]} :Runtime error: Index out of bounds} \tn % Row Count 6 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{match =\textgreater{} arms; arm : pattern =\textgreater{} code}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{match \seqsplit{guess.cmp(\&secret\_number)} \{ =\textgreater{} arms \newline Ordering::Less =\textgreater{} println!("Too small!"), //pattern =\textgreater{} code \newline Ordering::Greater =\textgreater{} println!("Too big!"), \newline Ordering::Equal =\textgreater{} \{ //code block \newline println!("You win!"); \newline \newline \} \newline \} \newline //similar to switch case? but concise !} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.41887 cm} x{2.42581 cm} p{0.73232 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Integer Types}} \tn % Row 0 \SetRowColor{LightBackground} Length & Signed & \seqsplit{Unsigned} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} 8-bit & i8 & u8 \tn % Row Count 3 (+ 1) % Row 2 \SetRowColor{LightBackground} 16-bit & i16 & u16 \tn % Row Count 4 (+ 1) % Row 3 \SetRowColor{white} 32-bit & i32 & u32 \tn % Row Count 5 (+ 1) % Row 4 \SetRowColor{LightBackground} 64-bit & i64 & u64 \tn % Row Count 6 (+ 1) % Row 5 \SetRowColor{white} arch & isize & usize \tn % Row Count 7 (+ 1) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-} \tn % Row Count 8 (+ 1) % Row 7 \SetRowColor{white} \mymulticolumn{3}{x{5.377cm}}{arch 32/64 bit system - isize =i32/64, usize=u32/u64} \tn % Row Count 10 (+ 2) % Row 8 \SetRowColor{LightBackground} Signed & -(2\textasciicircum{}n - 1\textasciicircum{}) to 2\textasciicircum{}n - 1\textasciicircum{} - 1 & \tn % Row Count 12 (+ 2) % Row 9 \SetRowColor{white} Unsigned & 0 to 2\textasciicircum{}n\textasciicircum{}-1 & \tn % Row Count 13 (+ 1) % Row 10 \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{arch (useful in indexing collections)} \tn % Row Count 14 (+ 1) % Row 11 \SetRowColor{white} type suffix & 57u8 & \tn % Row Count 15 (+ 1) % Row 12 \SetRowColor{LightBackground} visual separator & 1\_000 & \tn % Row Count 17 (+ 2) % Row 13 \SetRowColor{white} \mymulticolumn{3}{x{5.377cm}}{default type is u32 even on 64bit arch} \tn % Row Count 18 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Functions {\bf{fn}}}} \tn % Row 0 \SetRowColor{LightBackground} snake case - lowercase words separated by (\_) underscore & `fn one\_two() \{ \}` \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} parameters: name {\bf{:}} type & `fn foo\_bar(x: i32, y:u32) \{ \}` \tn % Row Count 5 (+ 2) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{statement vs expression} \tn % Row Count 6 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{statement ends with ; and does not evaluate to a value;} \tn % Row Count 8 (+ 2) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{expression doesn't end with ; and evaluates to a value} \tn % Row Count 10 (+ 2) % Row 5 \SetRowColor{white} code block expression \{\} x+1 is expression which is returned & `let y = \{ let x = 3; x + 1 \}` value of y will be 4; \tn % Row Count 14 (+ 4) % Row 6 \SetRowColor{LightBackground} Error: expected expression, found statement (`let`) & `let a = (let b =2);` \tn % Row Count 17 (+ 3) % Row 7 \SetRowColor{white} functions with return value -\textgreater{} type & `fn five() -\textgreater{} i32 \{ 5 \};` 5 is expression as no colon, and return value as it's last expression \tn % Row Count 22 (+ 5) % Row 8 \SetRowColor{LightBackground} `fn plus\_one(x: i32) -\textgreater{} i32 \{ x + 1; \}` & ; turns into statement, and empty tuple () will returned, will be a compiler error as () is not i32 \tn % Row Count 27 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{enums - methods}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{enum Message \{ \newline Quit, \newline Move \{ x: i32, y: i32 \}, \newline Write(String), \newline ChangeColor(i32, i32, i32), \newline \} \newline impl Message \{ \newline fn call(\&self) \{ \newline // method body would be defined here \newline \} \newline \} \newline \newline let m = \seqsplit{Message::Write(String::from("hello"));} \newline m.call();} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{options\textless{}T\textgreater{} alternate Null implementation}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{enum Option\textless{}T\textgreater{} \{ \newline Some(T), \newline None, \newline \} \newline let some\_number = Some(5); \newline let some\_string = Some("a string"); \newline let absent\_number: Option\textless{}i32\textgreater{} = None; \newline \newline //error \newline let x: i8 = 5; \newline let y: Option\textless{}i8\textgreater{} = Some(5); \newline \newline let sum = x + y; //error as x and y are two different types \newline error{[}E0277{]}: the trait bound `i8: std::ops::Add\textless{}std::option::Option\textless{}i8\textgreater{}\textgreater{}` is not satisfied} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{match - \_ placeholder}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{let some\_u8\_value = 0u8; \newline match some\_u8\_value \{ \newline 1 =\textgreater{} println!("one"), \newline 3 =\textgreater{} println!("three"), \newline 5 =\textgreater{} println!("five"), \newline 7 =\textgreater{} println!("seven"), \newline \_ =\textgreater{} (), unit value \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Control flow - if \{ \} else if \{ \} else \{ \}}} \tn % Row 0 \SetRowColor{LightBackground} if number == 3 \{ \} & arm \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} condition should evaluate to bool type & or mismatched types error \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} if condition \{ \} else if condition \{ \} else \{ \} & blocks of code called arms \tn % Row Count 6 (+ 3) % Row 3 \SetRowColor{white} let a = if a == 3 \{ 2 \} else \{ 5\} & expressions in all arms should evaluate to same type \tn % Row Count 9 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{match handling Result}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{let guess: u32 = match guess.trim().parse() \{ \newline Ok(num) =\textgreater{} num, //Ok receives num from return Result, which is returned by match \newline Err(\_) =\textgreater{} continue, // \_ underscore catches all values \newline \};} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{println!}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{No argument indices.. just simple brace \{\}} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{`println!("x = \{\} and y = \{\}", x, y);`} \tn % Row Count 2 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.63781 cm} x{2.33919 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Control flows - while and for}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{`while number != 3 \{ number = number +1; \}`} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{`let a ={[}1,2{]}; for element in a.iter() \{ \} `} \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} `for number in (1..4).rev() \{` & alternate approach to while \tn % Row Count 4 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Ownership}} \tn % Row 0 \SetRowColor{LightBackground} My first reaction to the concept of Ownership & WOW! \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} Value has a variable & Owner \tn % Row Count 4 (+ 1) % Row 2 \SetRowColor{LightBackground} When owner goes out of scope & Value is dropped \tn % Row Count 6 (+ 2) % Row 3 \SetRowColor{white} variable assignment, Passing to as function parameter or returning from function, it is moved. & `let s1 = \seqsplit{String::from("hello");} let s2 = s1;` s1 is no longer valid. It is moved. Only s2 is the owner \tn % Row Count 12 (+ 6) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{error{[}E0382{]}: use of moved value: `s1`} \tn % Row Count 13 (+ 1) % Row 5 \SetRowColor{white} Reference doesn't have ownership & when it goes out of scope, nothing happens. \tn % Row Count 16 (+ 3) % Row 6 \SetRowColor{LightBackground} Pass by reference & it is not moved. It's just borrowed. \tn % Row Count 18 (+ 2) % Row 7 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{References are immutable by default} \tn % Row Count 19 (+ 1) % Row 8 \SetRowColor{LightBackground} Mutable References & `fn main() \{ \{\{nl\}\} let mut s = \seqsplit{String::from("hello");} change({\bf{\&mut s}}); \} \{\{nl\}\} fn \seqsplit{change(some\_string:} {\bf{\&mut String}}) \{ \seqsplit{some\_string.push\_str("}, world"); \}` \tn % Row Count 28 (+ 9) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Memory is managed through a system of ownership with a set of rules that the compiler checks at compile time. At compile time!!!} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Cargo}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{`cargo -{}-version`} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{`cargo new hello\_cargo -{}-bin` creates `Cargo.toml` and main.rs} \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{-{}-bin=bin(ary) or library.} \tn % Row Count 4 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{source control: default git -{}-vcs=} \tn % Row Count 5 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Cargo is Rust's build system and package manager.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Cargo.toml}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{[}package{]} \newline name = "hello\_cargo" \#name of the executable \newline version = "0.1.0" \#version \newline authors = {[}"Your Name \textless{}you@example.com\textgreater{}"{]} \#Cargo gets name and email from the environment \newline \newline {[}dependencies{]} \#packages aka crates} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{TOML: Tom's Obvious, Minimal Language} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{import crate toml}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{[}dependencies{]} \newline rand = "0.3.14" \# SimVer \textasciitilde{} \textasciicircum{}0.3.14 any version that is compatible with 0.3.14} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Adding crates to toml file.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{cargo build , cargo run , cargo check}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{`cargo build \# creates an executable file in \seqsplit{target/debug/hello\_cargo`}} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{`cargo run \# build and run`} \tn % Row Count 3 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{`cargo check \#compilation check, no building executable`} \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{`cargo build -{}-release`} \tn % Row Count 6 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{error{[}E0308{]}: mismatched types}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{error{[}E0308{]}: mismatched types -{}-\textgreater{} src/main.rs:23:21 \newline \newline match \seqsplit{guess.cmp(\&secret\_number)} \newline \textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{}\textasciicircum{} expected struct `std::string::String`, found integral variable \newline \newline = note: expected type `\&std::string::String` \newline = note: found type `\&\{integer\}`} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} p{0.4977 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{cargo.lock}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Cargo maintains versions in cargo.lock file} \tn % Row Count 1 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} p{0.4977 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{cargo update}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{cargo updates all versions upto next symver} \tn % Row Count 1 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{registry}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Cargo fetches external dependencies and their dependencies from registry, a copy from the crates.io.} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{crates.io is a public repo} \tn % Row Count 3 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} p{0.4977 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{loop}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{loop \{ \}} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{`break;` exits the loop} \tn % Row Count 2 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{cargo test}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\#{[}cfg(test){]} \newline mod tests \{ \newline \#{[}test{]} -{}-\textgreater{} test \newline fn it\_works() \{ \newline assert\_eq!(2 + 2, 4); \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Doc-tests adder documentation tests? to have examples \newline assert! false value, assetseq! == assertive! != \newline {[}should\_panic{]} to expect panic! \newline {[}ignore{]} \newline cargo test -{}- -{}-test-threads=1 stop parallel run \newline cargo test -{}-nocapture , no print output \newline cargo test add //runs tests containing add} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.68758 cm} x{2.28942 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{tests organization}} \tn % Row 0 \SetRowColor{LightBackground} `\#{[}cfg(test){]} mod tests \{ \}` & compile only cfg is test \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} tests folder & integration tests \tn % Row Count 3 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{struct}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{struct User \{ \newline username: String, field =\textgreater{} name :type \newline email: String, \newline sign\_in\_count: u64, \newline active: bool, \newline \} \newline // Instantiating \newline let user1 = User \{ //struct name \newline email: \seqsplit{String::from("someone@example}.com"), //and \newline username: \seqsplit{String::from("someusername123")}, \newline active: true, \newline sign\_in\_count: 1, \newline \}; \newline //dot notation \newline let mut user2 = User \{ \}; \newline user2.email = \seqsplit{String::from("someone@example}.com");} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{unit-like structs without fileds () .. Used to implement traits with out data on the type. \newline \newline ownership - lifetimes?} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{1.09494 cm} x{3.88206 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Comments}} \tn % Row 0 \SetRowColor{LightBackground} // & /* */ \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{//! //} \tn % Row Count 2 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{tuple structs}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{struct Color(i32, i32, i32); \newline struct Point(i32, i32, i32); \newline \newline let black = Color(0, 0, 0); \newline let origin = Point(0, 0, 0);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{struct - instantiating options}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{// {\bf{..}} shorthand \newline let user2 = User \{ \newline email: \seqsplit{String::from("another@example}.com"), \newline username: \seqsplit{String::from("anotherusername567")}, \newline ..user1 // .. remaining fields should be from user1 instance \newline \}; \newline // shorthand - when variables and fields have same names \newline let email =""; \newline let user2 = User \{ \newline email //shortHand \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{struct methods}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{struct Rectangle \{ \newline width: u32, \newline height: u32, \newline \} \newline \newline impl Rectangle \{ \newline fn area(\&self) -\textgreater{} u32 \{ //first parameter should be self , instance of the struct \newline self.width * self.height \newline \} \newline \newline \newline fn square(size: u32) -\textgreater{} Rectangle \{ //associated function Rectangle::square \newline Rectangle \{ width: size, height: size \} \newline \} \newline \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\&mut self to modify struct} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{struct \#{[}derive(Debug){]}}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{println!("rect1 is \{\}", rect1);} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{error{[}E0277{]}: the trait bound `Rectangle: std::fmt::Display` is not satisfied} \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\{:?\} ? to use Debug Trait} \tn % Row Count 4 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{`\#{[}derive(Debug){]} \{\{nl\}\} struct Rectangle \{ \{\{nl\}\} width: u32, height: u32 \{\{nl\}\}\}`} \tn % Row Count 6 (+ 2) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\{:\#?\} to pretty print} \tn % Row Count 7 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Derived Traits} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{struct as expression}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{fn build\_user(email: String, username: String) -\textgreater{} User \{ \newline User \{ \newline email: email, \newline username: username, \newline active: true, \newline sign\_in\_count: 1, \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{modules}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{mod network \{ \newline fn connect() \{ \newline \} \newline \newline mod client \{ //nested module \newline fn connect() \{ \newline \} \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\seqsplit{network::client::connect();} \newline network:connect();} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{module - referencing a submodule}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{mod client; =\textgreater{} mod client \{ {\bf{//client.rs contents here}} \} \newline mod network \{ \newline //snippet \newline \} \newline //contents of clents.rs \newline fn connect \{ // {\bf{No need to add mod declaration }} \newline \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{modules-tree}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{communicator \newline ├── client \newline └── network \newline └── server \newline └── src \newline ├── client.rs \newline ├── lib.rs // mod client; mod network; \newline └── network \newline ├── mod.rs mod server; \newline └── server.rs} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{modules- rules}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{└── foo \newline ├── bar.rs (contains the declarations in `foo::bar`) \newline └── mod.rs (contains the declarations in `foo`, including `mod bar`)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{If a module named foo has no submodules, you should put the declarations for foo in a file named foo.rs. \newline \newline If a module named foo does have submodules, you should put the declarations for foo in a file named foo/mod.rs.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{pub - privacy rules}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{If an item is public} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}it can be accessed through any of its parent modules} \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{If an item is private} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}it can be accessed only by its immediate parent module and {\bf{any of the parent's child modules}}} \tn % Row Count 7 (+ 4) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{use}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{bring modules into scope. \newline pub mod a \{ \newline pub mod series \{ \newline pub mod of \{ \newline pub fn nested\_modules() \{\} \newline \} \newline \} \newline \} \newline fn main() \{ \newline \seqsplit{a::series::of::nested\_modules();} \newline \} \newline use a::series::of; \newline fn main() \{ \newline of::nested\_modules(); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{In use statement, paths are relative to the crate root by default \newline super:: confusing? if the module privacy rules state that parent and its immediate children of the parent can access private items, then why we need Super?} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Ownership - References Rules}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Only one mutable reference in a particular scope. Prevents datarace }} \newline let mut s = String::from("hello"); \newline let r1 = \&mut s; \newline let r2 = \&mut s; // {\emph{error{[}E0499{]}: cannot borrow {\bf{s}} as mutable more than once at a time }} \newline {\bf{ Combination of mutable and immutable references are not allowed. to guarantee immutability. }} \newline let mut s = String::from("hello"); \newline let r1 = \&s; // no problem \newline let r2 = \&s; // no problem \newline let r3 = \&mut s; // error{[}E0502{]}: cannot borrow {\bf{s}} as mutable because it is also borrowed as immutable} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{One mutable reference restriction prevents data race. \newline Only All Readers or just One Writer are allowed.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Dangling References}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{fn main() \{ \newline let reference\_to\_nothing = dangle(); \newline \} \newline fn dangle() -\textgreater{} \&String \{ \newline let s = String::from("hello"); \newline \&s // It is returning reference, borrowed value.. requiring s to be live outside this scope \newline \} //Compiler check} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{error{[}E0106{]}: missing lifetime specifier \newline = help: this function's return type contains a borrowed value, but there is \newline no value for it to be borrowed from \newline = help: consider giving it a 'static lifetime} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Slices}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{fn main() \{ \newline let mut s = String::from("hello world"); \newline let word = first\_word(\&s); \newline s.clear(); // Error! \newline \} \newline fn first\_word(s: \&String) -\textgreater{} \&str //immutable \{ \newline let bytes = s.as\_bytes(); \newline for (i, \&item) in bytes.iter().enumerate() \{ \newline if item == b' ' \{ \newline return \&s{[}0..i{]}; //borrowed as immutable \newline \} \newline \} \newline \&s{[}..{]} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{error{[}E0502{]}: cannot borrow {\bf{s}} as mutable because it is also borrowed as immutable. \newline Slicing : {[}..1{]} to start at 0, {[}2..{]} to the end.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{enums}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{enum IpAddrKind \{ \newline V4, \newline V6, \newline \} \newline struct IpAddr \{ \newline kind: IpAddrKind, // type \newline address: String, \newline \} \newline let home = IpAddr \{ \newline kind: IpAddrKind::V4, \newline address: \seqsplit{String::from("127.0.0.1")}, \newline \}; \newline let loopback = IpAddr \{ \newline kind: IpAddrKind::V6, \newline address: String::from("::1"), \newline \};} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{enums - variations}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{enum IpAddr \{ \newline V4(u8, u8, u8, u8), \newline V6(String), \newline \} \newline struct Ipv4Addr \{ \newline // -{}-snip-{}- \newline \} \newline struct Ipv6Addr \{ \newline // -{}-snip-{}- \newline \} \newline enum IpAddr \{ \newline V4(Ipv4Addr), \newline V6(Ipv6Addr), \newline \} \newline enum Message \{ \newline Quit, \newline Move \{ x: i32, y: i32 \}, \newline Write(String), \newline ChangeColor(i32, i32, i32), \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{enum - bringing some variants into scope}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{enum TrafficLight \{ \newline Red, \newline Yellow, \newline Green, \newline \} \newline \newline use TrafficLight::\{Red, Yellow\}; \newline \newline fn main() \{ \newline let red = Red; \newline let yellow = Yellow; \newline let green = TrafficLight::Green; \newline \} \newline or \newline use TrafficLight::*;} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{glob operator * to bring all items in a namespace.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{match - enum}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{enum Coin \{ \newline Penny, \newline Nickel, \newline Dime, \newline Quarter(UsState), \newline \} \newline \newline fn value\_in\_cents(coin: Coin) -\textgreater{} u32 \{ \newline match coin \{ \newline Coin::Penny =\textgreater{} 1, \newline Coin::Nickel =\textgreater{} 5, \newline Coin::Dime =\textgreater{} 10, \newline Coin::Quarter(state) =\textgreater{} \{ // state value is bind to the variable \newline println!("State quarter from \{:?\}!", state); \newline 25 \newline \}, \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{if let}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{let some\_u8\_value = Some(0u8); \newline match some\_u8\_value \{ \newline Some(3) =\textgreater{} println!("three"), \newline \_ =\textgreater{} (), \newline \} \newline or \newline //if let concise for one pattern \newline if let Some(3) = some\_u8\_value \{ \newline println!("three"); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{vectors Vec\textless{}T\textgreater{}, vec! macro}} \tn % Row 0 \SetRowColor{LightBackground} `let v: Vec\textless{}i32\textgreater{} = Vec::new();` & annotate type when not initialized with data \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} `let v = vec!{[}1, 2, 3{]};` & macro vec! to create instance and hold data \tn % Row Count 6 (+ 3) % Row 2 \SetRowColor{LightBackground} ` let mut v = Vec::new(); v.push(5); v.push(6); ` & mut to update the vector. Rush infers the datatype from push. \tn % Row Count 10 (+ 4) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Inferring datatype from push?} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{fn function pointer}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Use existing functions in place of closure : \newline fn add\_one(x: i32) -\textgreater{} i32 \{ \newline x + 1 \newline \} \newline \newline fn do\_twice(f: fn(i32) -\textgreater{} i32, arg: i32) -\textgreater{} i32 \{ \newline f(arg) + f(arg) \newline \} \newline \newline fn main() \{ \newline let answer = do\_twice(add\_one, 5); \newline \newline println!("The answer is: \{\}", answer); \newline \} \newline \newline //return the closure \newline fn returns\_closure() -\textgreater{} Box\textless{}Fn(i32) -\textgreater{} i32\textgreater{} \{ \newline Box::new(|x| x + 1) \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Vector access elements}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{let v = vec!{[}1, 2, 3, 4, 5{]}; \newline let third: \&i32 = \&v{[}2{]}; =\textgreater{} access with reference \newline let third: Option\textless{}\&i32\textgreater{} = v.get(2); //return None \newline let hundredth: \&i32 = \&v{[}100{]}; //panic , use get \newline \newline // \newline let mut v = vec!{[}1, 2, 3, 4, 5{]}; \newline let first = \&v{[}0{]}; // immutable borrowing \newline v.push(6); //immutable borrow above line, it's error to borrow mutable reference again} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Vector iterator}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{let v = vec!{[}100, 32, 57{]}; \newline for i in \&v \{ \newline println!("\{\}", i); \newline \} \newline //mutable vector and {\emph{i to dereference using }} \newline let mut v = vec!{[}100, 32, 57{]}; \newline for i in \&mut v \{ \newline *i += 50; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Vector: enum to store different types}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{enum SpreadsheetCell \{ \newline Int(i32), \newline Float(f64), \newline Text(String), \newline \} \newline \newline let row = vec!{[} \newline SpreadsheetCell::Int(3), \newline \seqsplit{SpreadsheetCell::Text(String::from("blue"))}, \newline \seqsplit{SpreadsheetCell::Float(10}.12), \newline {]};} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{String, str}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{str: string literals are stored in the binary program. \newline format: UTF8 \newline OsString, OsStr, CString, and CStr are string variant libraries. \newline \newline //creating strings \newline let mut s = String::new(); \newline let s = "initial contents".to\_string(); //to\_string and from are matter of style \newline let s = String::from("initial contents"); \newline let hello = \seqsplit{String::from("नमस्ते");} //utf-8} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{String update and concatenation +/ format!}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{let mut s = String::from("foo"); \newline s.push\_str("bar"); // foobar append , it takes slice so no ownership transfer \newline \newline let mut s = String::from("lo"); \newline s.push('l'); //character , lol \newline // concatenation + \newline let s1 = String::from("Hello, "); \newline let s2 = String::from("world!"); \newline let s3 = s1 + \&s2; // Note s1 has been moved here and can no longer be used \newline fn add(self, s: \&str) -\textgreater{} String \{ // s2 string =\textgreater{} str deref coersion \&s2 =\textgreater{} \&s2{[}..{]} \newline //more than two string, use \newline let s1 = String::from("tic"); \newline let s2 = String::from("tac"); \newline let s3 = String::from("toe"); \newline \newline let s = format!("\{\}-\{\}-\{\}", s1, s2, s3);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} p{0.4977 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{strings indexing}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{`let s1 = String::from("hello"); let h = s1{[}0{]};`} \tn % Row Count 1 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{error{[}E0277{]}: the trait bound `std::string::String: std::ops::Index\textless{}\{integer\}\textgreater{}` is not satisfied \newline A String is a wrapper over a Vec\textless{}u8\textgreater{}. UTF8, 2 bytes for some characters, 1byte for some \newline \newline let len = \seqsplit{String::from("Hola").len();} =\textgreater{} 4 \newline \newline let len = \seqsplit{String::from("Здравствуйте")}.len(); =\textgreater{} 24} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Error - Recoverable Result, Unrecoverable panic!}} \tn % Row 0 \SetRowColor{LightBackground} `RUST\_BACKTRACE=1 cargo run` & stack trace ? (enable debug symbols) \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} Err(ref error) if error.kind() == ErrorKind::NotFound =\textgreater{} & error.kind() \tn % Row Count 5 (+ 3) % Row 2 \SetRowColor{LightBackground} unwrap & error =\textgreater{} panic, ok=\textgreater{} returns value \tn % Row Count 7 (+ 2) % Row 3 \SetRowColor{white} expect & message when error occurs \tn % Row Count 9 (+ 2) % Row 4 \SetRowColor{LightBackground} `let mut f = \seqsplit{File::open("hello.txt")?;`} & ? to propagate error. From trait. From::from, error type should implement from \tn % Row Count 13 (+ 4) % Row 5 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{\seqsplit{`File::open("hello.txt")?.read\_to\_string(\&mut} s)?;`} \tn % Row Count 15 (+ 2) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{? for return type Result} \tn % Row Count 16 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Stack unwinding - \newline {[}profile.release{]} \newline panic = 'abort'} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Cargo in depth}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{//Cargo profiles \newline {[}profile.dev{]} \newline opt-level = 0 //overriding defaults \newline \newline {[}profile.release{]} \newline opt-level = 3 \newline \newline //re exporting API \newline pub use kinds::PrimaryColor; \newline pub use kinds::SecondaryColor; \newline pub use utils::mix; \newline \newline cargo.io login: cargo login \seqsplit{abcdefghijklmnopqrstuvwxyz012345} \newline unique package name to publish and cargo publish \newline cargo yank -{}-vers 1.0.1} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{HashMap\textless{}K, V\textgreater{}}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{use \seqsplit{std::collections::HashMap;} keys of the same type and values of the same type. \newline let mut scores = HashMap::new(); \newline \newline scores.insert(String::from("Blue"), 10); \newline scores.insert(String::from("Yellow"), 50); \newline \newline //creating a hash map from two vectors \newline let teams = vec!{[}String::from("Blue"), String::from("Yellow"){]}; \newline let initial\_scores = vec!{[}10, 50{]}; \newline \newline let scores: HashMap\textless{}\_, \_\textgreater{} = \seqsplit{teams.iter().zip(initial\_scores.iter()).collect();} \newline //HashMap to get the desired type from collect .. strange way of specifying return value \newline // \_, \_ Rust infers the data types of Key and Value \newline \newline //access value \newline let mut scores = HashMap::new(); \newline scores.insert(String::from("Blue"), 10); \newline scores.insert(String::from("Yellow"), 50); \newline let team\_name = String::from("Blue"); \newline let score = \seqsplit{scores.get(\&team\_name);} //get \newline \newline //iterating \newline for (key, value) in \&scores \{ \} \newline \newline //To only insert if key doesn't have a value \seqsplit{scores.entry(String::from("Yellow")).or\_insert(50);} //returns mutable reference \newline \newline // let count = \seqsplit{map.entry(word).or\_insert(0);} //to insert 0, for first time key insertion} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{BuildHasher type: default is cryptographically secure hashing, can be slow \newline Values are moved, and Hashmap takes the ownership of keys and values. \newline \newline Hasmap insert doesn't take the ownership. \newline insert of a existing key overrides the value} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Generic data types \textless{}T\textgreater{}}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{fn largest\textless{}T\textgreater{}(list: \&{[}T{]}) -\textgreater{} T \newline \newline struct Point\textless{}T\textgreater{} \{ \newline x: T, \newline y: T, \newline \} \newline \newline struct Point\textless{}T, U\textgreater{} \{ \newline x: T, \newline y: U, \newline \} \newline \newline enum Option\textless{}T\textgreater{} \{ \newline Some(T), \newline None, \newline \} \newline \newline struct Point\textless{}T\textgreater{} \{ \newline x: T, \newline y: T, \newline \} \newline \newline \newline impl\textless{}T\textgreater{} Point\textless{}T\textgreater{} \{ \newline fn x(\&self) -\textgreater{} \&T \{ \newline \&self.x \newline \} \newline \} \newline \newline impl Point\textless{}f32\textgreater{} \{ //specific type \newline fn \seqsplit{distance\_from\_origin(\&self)} -\textgreater{} f32 \{ \newline (self.x.powi(2) + self.y.powi(2)).sqrt() \newline \} \newline \} \newline \newline struct Point\textless{}T, U\textgreater{} \{ \newline x: T, \newline y: U, \newline \} \newline //mixup \newline impl\textless{}T, U\textgreater{} Point\textless{}T, U\textgreater{} \{ \newline fn mixup\textless{}V, W\textgreater{}(self, other: Point\textless{}V, W\textgreater{}) -\textgreater{} Point\textless{}T, W\textgreater{} \{ \newline Point \{ \newline x: self.x, \newline y: other.y, \newline \} \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Monomorphization to specify concrete code at compile time} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{trait}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{pub trait Summary \{ \newline fn \seqsplit{summarize\_author(\&self)} -\textgreater{} String; \newline \newline fn summarize(\&self) -\textgreater{} String \{ \newline format!("(Read more from \{\}...)", \seqsplit{self.summarize\_author())} //default can call other methods in the trait. \newline \} \newline \} \newline \newline pub struct NewsArticle \{ \newline pub headline: String, \newline pub location: String, \newline pub author: String, \newline pub content: String, \newline \} \newline \newline impl Summary for NewsArticle \{ \newline fn summarize(\&self) -\textgreater{} String \{ \newline format!("\{\}, by \{\} (\{\})", self.headline, self.author, self.location) \newline \} \newline \} \newline \newline pub struct Tweet \{ \newline pub username: String, \newline pub content: String, \newline pub reply: bool, \newline pub retweet: bool, \newline \} \newline \newline impl Summary for Tweet \{ //for \newline fn summarize(\&self) -\textgreater{} String \{ \newline format!("\{\}: \{\}", self.username, self.content) \newline \} \newline \} \newline //default implementation \newline fn summarize(\&self) -\textgreater{} String \{ \newline String::from("(Read more...)") \newline \} \newline \newline //to use default implementation, \newline impl Summary for NewsArticle \{\} //empty block} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{we can implement a trait on a type only if either the trait or the type is local to your crate. \newline coherence/orphan rule:people's code can't break your code and vice versa} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Generic constraints}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{// + \newline fn some\_function\textless{}T: Display + Clone, U: Clone + Debug\textgreater{}(t: T, u: U) -\textgreater{} i32 \{ \newline \newline //where clause: with mutilple trait bounds \newline fn some\_function\textless{}T, U\textgreater{}(t: T, u: U) -\textgreater{} i32 \newline where T: Display + Clone, \newline U: Clone + Debug \newline \{} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Conditionally implement on bounds: impl\textless{}T: Display + PartialOrd\textgreater{} Pair\textless{}T\textgreater{} \{} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{lifetimes}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\{ \newline let r; \newline \{ \newline let x = 5; \newline r = \&x; \newline \} \newline println!("r: \{\}", r); \newline \} \newline error{[}E0597{]}: x does not live long enough \newline \newline fn longest(x: \&str, y: \&str) -\textgreater{} \&str \{ \newline if x.len() \textgreater{} y.len() \{ \newline x \newline \} else \{ \newline y \newline \} \newline \} \newline error{[}E0106{]}: missing lifetime specifier \newline //lifetime annotations with generics -{}- means all x, y are has the same lifetime \newline fn longest\textless{}'a\textgreater{}(x: \&'a str, y: \&'a str) -\textgreater{} \&'a str \{ \newline if x.len() \textgreater{} y.len() \{ \newline x \newline \} else \{ \newline y \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{smaller lifetime is chosen. \newline static - let s: \&'static str = "I have a static lifetime.";} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Iterator}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{trait Iterator \{ \newline type Item; \newline \newline fn next(\&mut self) -\textgreater{} Option\textless{}Self::Item\textgreater{}; \newline \newline // methods with default implementations elided \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{1.The iter method produces an iterator over immutable references. \newline 2. into\_iter to take over ownership of the parent and returns owned values \newline 3. iter\_mut - iterate over mutable references \newline 4. consuming adaptors -\textgreater{} uses up iterator such as sum() \newline 5. chain of iterator adaptors following a consumer adaptor gets you the results (ex: collect()) \newline 6.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.75186 cm} x{1.29487 cm} x{1.2531 cm} x{0.87717 cm} } \SetRowColor{DarkBackground} \mymulticolumn{4}{x{5.377cm}}{\bf\textcolor{white}{Box\textless{}T\textgreater{}, RC\textless{}T\textgreater{}, RefCell\textless{}T\textgreater{}}} \tn % Row 0 \SetRowColor{LightBackground} RC\textless{}T\textgreater{} & Box\textless{}T\textgreater{} & RefCell\textless{}T\textgreater{} & \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \seqsplit{multiple} & Single & Single & Data \seqsplit{Ownership} \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} \seqsplit{immutable} & immutable or mutable & immutable or mutable & \seqsplit{Borrowing} \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} \seqsplit{compile} time & compile time & runtime & checked at \tn % Row Count 7 (+ 2) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{4}{x{5.377cm}}{Because RefCell\textless{}T\textgreater{} allows mutable borrows checked at runtime, we can mutate the value inside the RefCell\textless{}T\textgreater{} even when the RefCell\textless{}T\textgreater{} is immutable} \tn % Row Count 10 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}----} \SetRowColor{LightBackground} \mymulticolumn{4}{x{5.377cm}}{let y = \&mut x;? let mut y = x; confusion?} \tn \hhline{>{\arrayrulecolor{DarkBackground}}----} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{threads}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{let handle = std::thread::spawn(|| \{ //spawn new thread \newline for i in 1..10 \{ \newline println!("hi number \{\} from the spawned thread!", i); \newline \seqsplit{std::thread::sleep(std::time::Duration::from\_millis(1));} \newline \} \newline \}); \newline handle.join().unwrap(); //wait to finish \newline let v = vec!{[}1, 2, 3{]}; \newline \newline let handle = thread::spawn(move || \{ =\textgreater{} to let capture take the ownership \newline println!("Here's a vector: \{:?\}", v); \newline \}); \newline error{[}E0373{]}: closure may outlive the current function, but it borrows v, \newline which is owned by the current function \newline after move drop(v) \textasciicircum{} error value used here after move} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{JoinHandle is an owned value ?} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.9908 cm} x{2.9862 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Closures - Environment capture - Traits}} \tn % Row 0 \SetRowColor{LightBackground} Taking ownership {\bf{FnOnce}} & as it takes ownership of variables it uses from the environment, closure can be called once \tn % Row Count 4 (+ 4) % Row 1 \SetRowColor{white} Borrowing mutably {\bf{FnMut}} & It borrows mutably, so it can change the environment \tn % Row Count 7 (+ 3) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Borrowing immutably "Fn"} \tn % Row Count 8 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Can FnMut be called multiple times? (which tries borrow mutably in every call) Yes, as call finishes, the variables are available for borrowing. \newline let equal\_to\_x = move |z| z == x; to move the ownership of x to the closure.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{threads - channel mpsc}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{use std::sync::mpsc; \newline \newline let (tx, rx) = mpsc::channel(); tx: transmitter, rx: receiver \newline \newline thread::spawn(move || \{ \newline let val = String::from("hi"); \newline \seqsplit{tx.send(val).unwrap();//send} takes the ownership of val \newline \}); \newline \newline let tx1 = \seqsplit{mpsc::Sender::clone(\&tx);} //clone a transmitter} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{mpsc : multiple producer, single consumer =\textgreater{} multiple senders and one receiver} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Mutex\textless{}T\textgreater{} , Arc\textless{}T\textgreater{}}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{let counter = Arc::new(Mutex::new(0)); \newline let mut handles = vec!{[}{]}; \newline \newline for \_ in 0..10 \{ \newline let counter = Arc::clone(\&counter); //clone \newline let handle = thread::spawn(move || \{ \newline let mut num = counter.lock().unwrap(); \newline \newline *num += 1; \newline \}); \newline handles.push(handle); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Sync and Send}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{concurrency is part of the standard library not the language.} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{two concurrency concepts embedded in the language: the std::marker traits Sync and Send} \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} The Send marker trait indicates that ownership of the type implementing Send can be transferred between threads & except Rc\textless{}T\textgreater{} multiple references but can't be shared between threads \tn % Row Count 10 (+ 6) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{The Sync marker trait indicates that it is safe for the type implementing Sync to be referenced from multiple threads} \tn % Row Count 13 (+ 3) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{In other words, any type T is Sync if \&T (a reference to T) is Send, meaning the reference can be sent safely to another thread} \tn % Row Count 16 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{closures}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{let expensive\_closure = |num: u32| -\textgreater{} u32 \{ \newline println!("calculating slowly..."); \newline \seqsplit{thread::sleep(Duration::from\_secs(2));} \newline num \newline \}; \newline \newline // type inference \newline let example\_closure = |x| x; \newline \newline let s = \seqsplit{example\_closure(String::from("hello"));} \newline let n = example\_closure(5); //error type inference only one type \newline // memoization or lazy evaluations \newline impl\textless{}T\textgreater{} Cacher\textless{}T\textgreater{} \newline where T: Fn(u32) -\textgreater{} u32 \newline \{ \newline fn new(calculation: T) -\textgreater{} Cacher\textless{}T\textgreater{} \{ \newline Cacher \{ \newline calculation, \newline value: None, \newline \} \newline \} \newline \newline fn value(\&mut self, arg: u32) -\textgreater{} u32 \{ \newline match self.value \{ \newline Some(v) =\textgreater{} v, \newline None =\textgreater{} \{ \newline let v = (self.calculation)(arg); \newline self.value = Some(v); \newline v \newline \}, \newline \} \newline \} \newline \} \newline let mut expensive\_result = Cacher::new(|num| \{ \newline println!("calculating slowly..."); \newline \seqsplit{thread::sleep(Duration::from\_secs(2));} \newline num \newline \}); \newline \newline //memoization} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{unsafe}} \tn % Row 0 \SetRowColor{LightBackground} Implementing unsafe trait & `unsafe trait Foo \{ \} ` \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} & `unsafe impl Foo for i32 \{ \}` \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{mutating static is unsafe} \tn % Row Count 5 (+ 1) % Row 3 \SetRowColor{white} extern "C" \{ \} Foreign Function Interface (FFI) & call in unsafe block \tn % Row Count 8 (+ 3) % Row 4 \SetRowColor{LightBackground} C : application binary interface (ABI) & `extern "C" \{ fn abs(input: i32) -\textgreater{} i32; \}` \tn % Row Count 11 (+ 3) % Row 5 \SetRowColor{white} Calling Rust from other languages & `\#{[}no\_mangle{]} \{\{nl\}\} pub extern "C" fn call\_from\_c() \{ \{\{nl\}\} println!("Just called a Rust function from C!"); \{\{nl\}\} \}` \tn % Row Count 18 (+ 7) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{unsafe block to call unsafe functions} \tn % Row Count 19 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{1. Dereference a raw pointer \newline 2. Call an unsafe function or method \newline 3. Access or modify a mutable static variable \newline 4. Implement an unsafe trait} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Raw pointers}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Different from references and smart pointers, keep in mind that raw pointers: \newline \newline 1. Are allowed to ignore the borrowing rules and have both immutable and mutable pointers, or multiple mutable pointers to the same location \newline 2. Aren't guaranteed to point to valid memory \newline 3. Are allowed to be null \newline 4. Don't implement any automatic clean-up \newline \newline let mut num = 5; \newline \newline let r1 = \&num as {\emph{const i32; \newline let r2 = \&mut num as }}mut i32; \newline \newline unsafe \{ //dereferencing \newline println!("r1 is: \{\}", {\emph{r1); \newline println!("r2 is: \{\}", }}r2); \newline \} \newline \newline {\emph{const i32 and }}mut i32 raw pointers that both pointed to the same memory location, that of num. If instead we'd tried to create an immutable and a mutable reference to num, this would not have compiled because Rust's ownership rules don't allow a mutable reference at the same time as any immutable references. With raw pointers, can create mutable pointer and an immutable pointer to the same location, and change data through the mutable pointer, potentially creating a data race.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Lifetimes adv}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{In our definition of Parser, in order to say that 's (the lifetime of the string slice) is guaranteed to live at least as long as 'c (the lifetime of the reference to Context), we change the lifetime declarations to look like this: \newline \newline \newline struct Parser\textless{}'c, {\bf{'s: 'c}}\textgreater{} \{ \newline context: \&'c Context\textless{}'s\textgreater{}, \newline \} \newline // lifetime bounds on references to Generic Types \newline struct StaticRef\textless{}T: 'static\textgreater{}(\&'static T); \newline \newline struct Ref\textless{}'a, T: 'a\textgreater{}(\&'a T); \newline \newline //Inference of Tait life times \newline The default lifetime of a trait object is 'static. \newline With \&'a Trait or \&'a mut Trait, the default lifetime is 'a. \newline With a single T: 'a clause, the default lifetime is 'a. \newline With multiple T: 'a-like clauses, there is no default; we must be explicit. \newline Box\textless{}Red + 'a\textgreater{} or Box\textless{}Red + 'static\textgreater{} \newline Just as with the other bounds, this means that any implementor of the Red trait that has references inside must have the same lifetime specified in the trait object bounds as those references} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Advanced Traits}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{pub trait Iterator \{ \newline type Item; // place holder \newline fn next(\&mut self) -\textgreater{} Option\textless{}Self::Item\textgreater{}; \newline \} \newline \newline //With Generic, needs to annotate the type \newline //Default generic type \newline trait Add\textless{}RHS=Self\textgreater{} \{ // RHS is self type a = a + a \newline type Output; \newline fn add(self, rhs: RHS) -\textgreater{} Self::Output; \newline \} \newline fn main() \{ \newline let person = Human; \newline Pilot::fly(\&person); //quality to avoid ambiguity \newline Wizard::fly(\&person); \newline person.fly(); \newline \} \newline \newline Assosciated functions: \newline //As no self, it can infer \newline \textless{}Dog as Animal\textgreater{}::baby\_name() \newline \newline //NewType \newline use tuple to creat traits on external types} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Implemented directly on the type has precedence over trait impls} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{3.23505 cm} x{1.74195 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Advanced Types}} \tn % Row 0 \SetRowColor{LightBackground} type Kilometers = i32; & Type aliases \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{let f: Box\textless{}Fn() + Send + 'static\textgreater{} = Box::new(|| println!("hi"));} \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{type Thunk = Box\textless{}Fn() + Send + 'static\textgreater{};} \tn % Row Count 4 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{type Result\textless{}T\textgreater{} = Result\textless{}T, std::io::Error\textgreater{};} \tn % Row Count 5 (+ 1) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{! never type = void} \tn % Row Count 6 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{iterating over string - bytes() and chars()}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{for c in \seqsplit{"नमस्ते".chars()} \{ \newline println!("\{\}", c); \newline \} \newline न \newline म \newline स \newline ् \newline त \newline े \newline \newline for b in \seqsplit{"नमस्ते".bytes()} \{ \newline println!("\{\}", b); \newline \} \newline 224 \newline 164 \newline // -{}-snip-{}- \newline 165 \newline 135} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Cargo workspaces}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{[}workspace{]} \newline members = {[} \newline "adder", \newline {]} \newline \newline ├── Cargo.lock \newline ├── Cargo.toml \newline ├── add-one \newline │ ├── Cargo.toml \newline │ └── src \newline │ └── lib.rs \newline ├── adder \newline │ ├── Cargo.toml \newline │ └── src \newline │ └── main.rs \newline └── target \newline \newline {[}dependencies{]} \newline add-one = \{ path = "../add-one" \} -{}- explicit \newline \newline cargo run -p adder //to run \newline \newline cargo install \$HOME/.cargo/bin \newline cargo-something =\textgreater{} cargo something} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{workspaces: all related crates share Cargo.lock and output directory. \newline dependencies should be added to cargo.toml files to extern crate} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}