Skip to content

Latest commit

 

History

History
86 lines (79 loc) · 2.71 KB

1.basics.md

File metadata and controls

86 lines (79 loc) · 2.71 KB

Basics of Program

  • Built-in Macro macro_name ! ( );
  • What are macros used for? They are used in metaprogramming, i.e., code that writes code. They look like functions in other system programming languages like C and C++, but instead of generating a function call like functions, they are expanded into source code that gets compiled with the rest of the program. In this way, they provide more run-time features.
  • Last-line of the method can have optional semi-colon in the end.

Basic formatting

  • Single Placeholders
  println!("Number: {}", 1);
  • Multiple Placeholders
    println!("{} is a {} girl", "Jane", "good");
  • Positional Arguments
 println!("Enhance your coding skills from {0} courses.  {0} courses are very {1}", "Educative", "interactive");
  • Named Arguments
 println!("{company} provides {kind} courses", company = "Educative", kind = "interactive");
  • Placeholder Traits {:b} - binary ,{:x} - hexadecimal, {:o} - octal
  println!("Number : 10 \nBinary:{:b} Hexadecimal:{:x} Octal:{:o}", 10, 10, 10);
  // 10 + 10 = 20
  • Basic expression formatting
  println!("{} + {} = {}",10, 10, 10 + 10);
  • Placeholder for a Debug Trait
  // You can use a debug trait and write as many values as desired within the parentheses.
  // This prevents having to write placeholders for each value.
  // {:?} is implemented via debug trait and can have limitation example `i32` array can be printed 
  //  if have more than 32 elements
  println!("{:?}", ("This is a Rust Course", 101));
  // ("This is a Rust Course", 101)
  // this is for pretty print
  println!("{:#?}", ("This is a Rust Course", 101));

Printing Styles

  • print!() macro simply prints the output to the console.
  • println!() macro appends a new line at the end of the string.
  • eprint!() macro displays the output as an error.
  • eprintln!() macro displays the output as an error and appends a new line(\n) at the end of it.

Comments

  • Line Comments
// line comment
  • Block Comments
/*
 Block comment
*/
  • Doc Comments
/// This is a Outer Doc comment outside the function
/// Generate docs for the following item.
/// This shows my code outside a module or a function
fn main() {
    //! This a Inner doc comment that is inside the function   
    //! This comment shows my code inside a module or a function  
    //! Generate docs for the enclosing item
    println!("{} can support {} notation","Doc comment","markdown");
}
  • memory print
use std::mem;
fn main(){
   let xs = [i32; 5] = [1,2,3,4,5];
   println!("{} {} {}", xs[0], xs.len(), mem::size_of_val(&xs));                    
}