Learn Rust Programming Language for Beginner

--

Hello World Program in Rust

fn main() {
println!("Hello, world!");
println!("I am a Software Engineer\nNew Line");
}

println! is a macro

Formatted Print — Printing is handled by various macros defined in std::fmt

  1. format! : write formatted text to string. To see the ouput of format!, you need to assign it in variable and the use print! or println!.
  2. print! : same as format! but the text is printed to the console(io::stdout).
  3. println! : same as print! but a new line is appended
  4. eprint! : same as print! but text is printed to the standard error(io::stderr)
  5. eprintln! : same as eprint! but a new line is appended

Example of format!

fn main() {
let _x = format!("alok Kumar");
println!("My name is {}",_x);
}

Output

Positional arguments in formatted print

fn main() {
// output - //Bob works at Google company
println!("{1} works at {0} company","Google","Bob");
}

Named arguments in Formatted Print

fn main() {
// output - Bob works at Google company
println!("{name} works at {company_name} company",company_name="Google",name="Bob");
}

Formatted output in different number system

fn main() {
/***
* Output
* Base 10 of 5678 - 5678
* Base 2 (binary) of 5678 - 1011000101110
* Base 8 (octal) of 5678 - 5678
* Base 16 (Hexadecimal) of 5678 - 162e
*Base 16 (Hexadecimal) of 5678 - 162E
*/
println!("Base 10 of 5678 - {}",5678);
println!("Base 2 (binary) of 5678 - {:b}",5678);
println!("Base 8 (octal) of 5678 - {:0}",5678);
println!("Base 16 (Hexadecimal) of 5678 - {:x}",5678);
println!("Base 16 (Hexadecimal) of 5678 - {:X}",5678);
}

Keep Note of Following in case of error

  • ``, which uses the `Display` trait
    — `?`, which uses the `Debug` trait
    — `e`, which uses the `LowerExp` trait
    — `E`, which uses the `UpperExp` trait
    — `o`, which uses the `Octal` trait
    — `p`, which uses the `Pointer` trait
    — `b`, which uses the `Binary` trait
    — `x`, which uses the `LowerHex` trait
    — `X`, which uses the `UpperHex` trait

Primitive Types in Rust with Examples

usize

--

--