0% found this document useful (0 votes)
191 views

Rust Cheat Sheet

The document discusses various Rust programming concepts including: 1. Comments, traits, enums, structs, tuples, arrays, functions, shadowing, mutability, casting, literals, type inference, conversions between types using From and Into traits, and conversions between types and strings using ToString and FromStr traits. 2. It provides code examples for each concept to demonstrate their usage, such as implementing a Summary trait, defining a Color enum with methods, defining a Point struct, creating tuple and array values, defining functions on structs and enums, examples of shadowing, mutable and immutable variables, type casting, numeric and string literals, and using From, Into, ToString and FromStr traits.

Uploaded by

newgmail account
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
191 views

Rust Cheat Sheet

The document discusses various Rust programming concepts including: 1. Comments, traits, enums, structs, tuples, arrays, functions, shadowing, mutability, casting, literals, type inference, conversions between types using From and Into traits, and conversions between types and strings using ToString and FromStr traits. 2. It provides code examples for each concept to demonstrate their usage, such as implementing a Summary trait, defining a Color enum with methods, defining a Point struct, creating tuple and array values, defining functions on structs and enums, examples of shadowing, mutable and immutable variables, type casting, numeric and string literals, and using From, Into, ToString and FromStr traits.

Uploaded by

newgmail account
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Comments-

// For single line comments let article = NewsArticle {


/* For headline: "News Article".to_string(),
multiline body: "This is the body of the
comments article".to_string(),
*/ };
Doc comment-
/// Generate library docs for the following let summary = summarize(&article);
item.
//! Generate library docs for the enclosing In rust type reference the data type.Every
item. value in rust has a type.

Formatted print- Debug-


formate!(“Hello formate macro”); In Rust, the debug attribute allows you to
print!(“Printing without newline”); use the {:?} formatting specifier to print out a
println!(“Printing with newline”); value in a human-readable format for
eprint!(“Printing with standard error”); debugging purposes. It can be applied to
eprintln!(“Printing with standard error and structs, enums, and other types.
newline”); #[derive(Debug)]
struct Point {
Trait- x: i32,
trait is a collection of methods that a type y: i32,
can implement. It defines a set of behaviors }
that a type can exhibit, and it allows you to The #[derive(Debug)] attribute tells the Rust
define generic code that works with any compiler to automatically implement the
type that implements the trait. Debug trait for the Point struct. This allows
Exm- you to print out values of the Point type
trait Summary { using the {:?} formatting specifier.
fn summarize(&self) -> String; let p = Point { x: 3, y: 4 };
} println!("{:?}", p);
struct NewsArticle { You can also implement the Debug trait
headline: String, manually for your own types by
body: String, implementing the fmt::Debug trait and the
} fmt::Formatter::debug_struct method. This
impl Summary for NewsArticle { allows you to customize the way your type
fn summarize(&self) -> String { is printed when using the {:?} formatting
format!("{}: {}", self.headline, self.body) specifier.
}
}
fn summarize(item: &impl Summary) ->
String {
item.summarize()
}
Tupple- -You can also define methods on enums by
tuple is a fixed-size collection of values of using the impl keyword
different type impl Color {
let t = (1, "hello", 3.14); fn mix(&self, other: &Color) -> Color {
let (x, y, z) = t; match (self, other) {
println!("x = {}, y = {}, z = {}", x, y, z); (Color::Red, Color::Blue) =>
let x = t.0; Color::Purple,
let y = t.1; (Color::Blue, Color::Red) =>
let z = t.2; Color::Purple,
println!("x = {}, y = {}, z = {}", x, y, z); (Color::Red, Color::Green) =>
Color::Yellow,
Array-an array is a fixed-size collection of (Color::Green, Color::Red) =>
values of the same type Color::Yellow,
let a = [1, 2, 3, 4, 5]; (Color::Green, Color::Blue) =>
let a = [0; 10]; Color::Cyan,
let x = a[2]; (Color::Blue, Color::Green) =>
Color::Cyan,
Sturct-a struct (short for "structure") is a _ => *self,
compound data type that allows you to }
group together related values }
struct Point { }
x: i32,
y: i32, This defines a method called mix on the
} Color enum that mixes two colors together
let p = Point { x: 3, y: 4 }; and returns the resulting color. You can call
let x = p.x; this method like this:
let y = p.y;
println!("x = {}, y = {}", x, y); let purple = Color::Red.mix(&Color::Blue);

impl Point { Shadowing-In Rust, the term "shadowing"


fn distance_to_origin(&self) -> f64 { refers to the practice of using a new variable
(self.x.pow(2) + self.y.pow(2)).sqrt() with the same name as an existing variable,
} thereby "shadowing" the original variable
} let x = 5;
let distance = p.distance_to_origin(); let x = x + 1;
let x = x * 2;
println!("x = {}", x);
Enum-An enum (short for "enumeration") is
a type that represents a fixed set of value //The final value of x is 12.
enum Color {
Red, Type-
Green, Casting-casting refers to the process of
Blue, converting a value of one type to a value of
} another type.
let x: i32 = 5; let x=5;
let y: f64 = x as f64;
Aliasing-In Rust, you can use the type
keyword to create an alias for an existing
Mutuality-In rust variable are mutable by type
default.For making a variable to immutable Here's an example of how to use the type
you have to be use “mut” keyword. keyword to create an alias for a tuple type:

let x=5; type Point = (i32, i32);


x=4; //Give you a compilation time error
cause here we are using by default mutable let p: Point = (0, 0);
variable
You can also use the type keyword to create
let mut x=5; an alias for a function type:
x=4; //No error will be provided
type BinOp = fn(i32, i32) -> i32;
Casting/Converting-
you can use the as keyword to perform a fn add(x: i32, y: i32) -> i32 {
type conversion, also known as casting. x+y
}
let x: i32 = 5;
let y: f64 = x as f64; fn subtract(x: i32, y: i32) -> i32 {
x-y
Literals- }

In Rust, a literal is a value written directly in let add_op: BinOp = add;


the source code. There are several types of let subtract_op: BinOp = subtract;
literals in Rust, including integers,
floating-point numbers, characters, strings, Conversion-
and boolean values. In Rust, the From and Into traits are used to
specify conversion between types. The
let x = 42; // x has the value 42 From trait allows you to convert a value of
let y = 0xff; // y has the value 255 (0xff is one type into a value of another type, while
hexadecimal notation) the Into trait allows you to convert a value of
let z = 0o77; // z has the value 63 (0o77 is one type into a value of another type and
octal notation) take ownership of the value in the process.
let w = 0b1111_0000; // w has the value 240
(0b1111_0000 is binary notation) From-
use std::convert::From;

Inference-Type inference in Rust is a #[derive(Debug)]


feature that allows the Rust compiler to struct Num {
automatically determine the type of a value value: i32,
based on the context in which it is used. }
To and from string-
impl From<i32> for Num { In Rust, you can use the ToString and
fn from(item: i32) -> Self { FromStr traits to convert values to and from
Num { value: item } strings. The ToString trait allows you to
} convert a value of a type to a String, while
} the FromStr trait allows you to convert a
String to a value of a type.
let num = Num::from(42);
println!("{:?}", num); // prints "Num { value: use std::string::ToString;
42 }"
#[derive(Debug)]
In this example, the Num struct has an impl struct Num {
block that implements the From<i32> trait value: i32,
for the Num type. This allows you to convert }
an i32 value into a Num value using the
‘From::from’ method. impl ToString for Num {
fn to_string(&self) -> String {
self.value.to_string()
Into- }
}
use std::convert::Into;
let num = Num { value: 42 };
#[derive(Debug)] let s = num.to_string();
struct Num { println!("{}", s); // prints "42"
value: i32,
}
use std::str::FromStr;
impl Into<i32> for Num {
fn into(self) -> i32 { #[derive(Debug)]
self.value struct Num {
} value: i32,
} }
//Fromstring
let num = Num { value: 42 }; impl FromStr for Num {
let x: i32 = num.into(); type Err = std::num::ParseIntError;
println!("{}", x); // prints "42"
fn from_str(s: &str) -> Result<Self,
In this example, the Num struct has an impl Self::Err> {
block that implements the Into<i32> trait for Ok(Num { value: s.parse()? })
the Num type. This allows you to convert a }
Num value into an i32 value using the }
Into::into method and take ownership of the
Num value in the process. let s = "42";
let num = Num::from_str(s).unwrap();
println!("{:?}", num); // prints "Num { value:
42 }" // Infinite loop
loop {
count += 1;
Expression-An expression is a piece of
code that returns a value. if count == 3 {
You can use the let keyword to bind the println!("three");
result of an expression to a variable.
let x = (5 + 2) * 3; // x is 21 // Skip the rest of this iteration
let y = let z = x + 1; // y is 22, z is 21 continue;
}
Flow control-
1.If-> println!("{}", count);

let x = 5; if count == 5 {
if x > 0 { println!("OK, that's enough");
println!("x is positive");
} else { // Exit this loop
println!("x is non-positive"); break;
} }
}
2.while-> }

let mut x = 0;

while x < 10 {
println!("x is {}", x); for loop-
x += 1;
} let fruits = ["apple", "banana", "orange"];
for fruit in fruits {
3.match-> println!("{}", fruit);
}
let x = 5;
match x {
0 => println!("x is zero"),
1...5 => println!("x is between 1 and 5"), Function-A function is a block of code that
_ => println!("x is something else"), performs a specific task and can be called
} by name.

Loop- fn add(x: i32, y: i32) -> i32 {


fn main() { x+y
let mut count = 0u32; }

println!("Let's count until infinity!");


Closure-In Rust, a closure is a function-like self-The `self` keyword refers to the current
value that can capture variables from its module scope
surrounding environment. super-The `super` keyword refers to the
parent scope
let add = |x: i32, y: i32| -> i32 { x + y };
trait MyTrait {
Module- fn my_method(&self);
mod my_module { }
pub mod submodule {
pub fn function() { struct MyStruct;
// ...
} impl MyTrait for MyStruct {
} fn my_method(&self) {
} println!("In MyStruct implementation of
MyTrait");
use my_module::submodule; }
}
submodule::function();
trait MyChildTrait: MyTrait {
Use/as- fn my_child_method(&self) {
self.my_method();
mod my_module { println!("In MyChildTrait");
pub struct MyStruct { }
// ... }
}
impl MyChildTrait for MyStruct {
pub fn function1() { fn my_method(&self) {
// ... super::my_method(self);
} println!("In MyStruct implementation of
MyChildTrait");
pub fn function2() { }
// ... }
}
} Generics-Generics are a way to write code
that can work with multiple types, rather
use my_module::{MyStruct as than being tied to a specific type. This
MyRenamedStruct, function1 as allows you to write more flexible and
my_function, *}; reusable code, and helps you avoid
duplicating code for different types.
fn main() {
let s = MyRenamedStruct { /* ... */ }; fn max<T: PartialOrd>(x: T, y: T) -> T {
my_function(); if x > y {
function2(); x
} } else {
y height: f64,
} }
}
impl Shape for Rectangle {
Here, T is the type parameter and fn area(&self) -> f64 {
PartialOrd is a trait constraint, which means self.width * self.height
that T must implement the PartialOrd trait in }
order to be used with this function. The
function takes two arguments x and y of fn perimeter(&self) -> f64 {
type T and returns a value of type T 2.0 * (self.width + self.height)
}
//Generic with struct }
struct Point<T> {
x: T, Here, we define a struct Rectangle and then
y: T, implement the Shape trait for Rectangle.
} This means that any Rectangle value now
has an area and a perimeter, and we can
Here, the Point struct has a type parameter call these methods on Rectangle values just
T that is used to specify the type of the x like any other method.
and y fields. This allows you to create Trait bounds are a way to specify that a
instances of Point with any type that is valid generic type must implement a particular
for the x and y fields. trait. For example

Trait-In Rust, a trait is a way to specify a set fn print_area<T: Shape>(shape: T) {


of behaviors that a type must implement. println!("The area is {}", shape.area());
Traits are similar to interfaces in other }
languages.
Here's an example of a trait definition in
Rust: The following is a list of derivable traits:

trait Shape { ● Comparison traits: Eq,


fn area(&self) -> f64;
PartialEq, Ord, PartialOrd.
fn perimeter(&self) -> f64;
} ● Clone, to create T from &T via a
copy.
This trait, Shape, defines two methods: area
and perimeter. Any type that implements the ● Copy, to give a type 'copy
Shape trait must provide an implementation semantics' instead of 'move
for these two methods.To implement a trait
semantics'.
for a type, you use the impl keyword, like
this: ● Hash, to compute a hash from &T.
● Default, to create an empty
struct Rectangle {
width: f64, instance of a data type.
● Debug, to format a value using the
{:?} formatter.

You might also like