root💀senseicat:~#

Hack. Eat. Sleep. Repeat!!!


Project maintained by SENSEiXENUS Hosted on GitHub Pages — Theme by mattgraham

Learning Rust

Installing Rust on LINUX CLI

curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

Printing Hello World!!!

fn main () {
   println!("Hello World!!!");
}

Compiling rust code with rustc

rustc -o <binary's name> <rust script's name>.rs

Or you can use

rustc try.rs

Cargo

Cargo is a package manager for Rust and it is used to install dependencies that your code requires.

### Checking Cargo’s version

 cargo --version

### Creating a directory to manage project with cargo containing directory for us: a Cargo.toml file and a srcdirectory with a main.rs file inside. It has also initialized a new Git repository along with a .gitignore file.

 cargo new <binary> --bin

### To compile Rust with cargo, from the directory, run with the command below and spot the binary in target/debug

 cargo build

### To build and run, use

 cargo run

To run and check for errors without creating a binary, use

 cargo check

To run and compile a rust code from github, use

$ git clone someurl.com/someproject
$ cd someproject
$ cargo build

Chapter 2: Building a Guessing game

Learning let,match and other methods

To import a library, use the keyword use and to use the specific library, use ::

use std::io;

To create a mutable variable, use mut and let to define a variable

let  mut foo = "bar"; ### Creating a variable to store string

let mut foo = String::new();

Using io to read lines and triggering a statement if the functions fails to read the line with .expect

‘&’ means reference in rust and it allows rust read data once without making it read multiple times.&mut guess is used instead of &guess to make it mutable.

io::stdin().read_line(&mut guess).expect("Failed to read lines");

Using println!() to insert values with placeholders

let x  = 9;
let y = 10;
println!("The x is {} and y is {}",x,y);

To update a crate, use

cargo update

To import a crate, use the keyword extern crate

extern crate rand
use std::cmp::Ordering

Comparing a number with std::cmp::Ordering

match guess.cmp(&secret_number){
      Ordering::Less => println!(""),
      Ordering::Greater => println!(""),
      Ordering::Equal => println!(""),
}

Some functions

Guessing game final code

extern crate rand;
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn main() {
   println!("Guessing game.....");
   let secret_number: u32  =  rand::thread_rng().gen_range(1,101);
   println!("The secret number is {}",secret_number);
   loop {
      let mut guess =  String::new();
      io::stdin().read_line(&mut guess)
         .expect("Enter a number.....!!!!");
      let guess: u32 = match guess.trim().parse() {
          Ok(num) => num,
          Err(_) => continue,
      };
      match guess.cmp(&secret_number) {
        Ordering::Less => println!("Lesser than the number"),
        Ordering::Equal => {
            println!("Equal to the number");
            break;
            },
        Ordering::Greater => println!("Greater than the number"),    
      }
   }    
}

Common Programming Concepts

This chapter explains the concepts like variables,functions, control flow, basic types and comments

Variables

Scalar Types

A Scalar type means a single point character. It can be an integer,floating-point number,Boolean and character

Integer types

An integer can be signed or unsigned. A signed integer can contain both negative and positive integers while unsigned ones can only contain non-negative integers.

length signed unsigned
8-bit i8 u8
16-bit i16 i16
32-bit i32 u32
64-bit i64 u64
Arch isize usize

Calculating the numbers that each length can store

Boolean

Character

Compound Types

Tuple

Array

Functions

Loops

Loop

Ownership

Rules:

Learning Ownership with String data type

Ways that data and variables interact: Move

Referencing and Dereferencing

Referencing is denoted by &, it does not take ownership of a variable’s value but just makes a reference to it e.g

    fn main() {
     let z = String::from("Hello");
     let length = calculate_length(&z);
     println!("The length of \"{}\" is {}",z,length);
  }
  fn calculate_length(s: &String) -> usize {
      return s.len()
  }

Mutable reference: Data race prevention in Rust

Dangling pointer

String Slices

It is used to grab to a part of a String.

Slicing an array

fn main() {
   let a = [1,3,4,5];
   let a1 = &a[0..3];
   println!("{:?}",a1);
}

Using struct to structure out data

Structs are more like tuple but are more flexible than the latter because you don’t have to rely on the order of data to get values.It is denoted by the keyword struct and contianed in curly braces.Then, inside the curly braces,we define the name,type of piece of data called fields.

Writing a function that returns a user Instance of a struct

//Function returning a struct instance
fn build_user(email: String,name: String) -> User {
    User {
        name: name,
        email: email,
        age: 10,
        is_active: false
    }
}

Using the update instance to add instances of a struct instance

The syntax ..<struct's instance specifies that the remaining fields not explicitly set should have the same value as the fields in the given instance.

 let mut user1 =  User {
     name: String::from("Ms Ilaro"),
     email: String::from("ZainabYassmineee"),
     age: -9,
     is_active: true
 };
 let mut user2 = User{
     name: String::from("Nardo@gmail.com"),
     email: String::from("wthisthat@gmail.com"),
     ..user1
 };

Struct tuple

Tuple structs are useful when you want to give more meaning to a tuple rather than creating a normal tuple e.g

 struct Name(String,String,String)

fn main() {
    struct Color(i32,i32,i32);
    struct Point(i32,i32,i32);
    let color1 =  Color(1,2,34);
    let point1 =  Point(1,2,34);
    println!("{},{}",point1.0,color1.1);
}

TRAITS in rust

A trait defines the functionality a particular type has and can share with other types. We can use traits to define shared behavior in an abstract way. We can use trait bounds to specify that a generic type can be any type that has certain behavior.

Printing a struct

Method Syntax

Method are declared like functions with the fn keyword but it is defined within the context of a struct.The first parameter of a method is self.

Associated functions

Associated functions allows us to declare methods within impl blocks without need to use the self parameter. They don’t have the instance of self to work with.They are called using this namespace syntax ::.String::from() is an associated function.