- 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.
println!("Number: {}", 1);
println!("{} is a {} girl", "Jane", "good");
println!("Enhance your coding skills from {0} courses. {0} courses are very {1}", "Educative", "interactive");
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));
- 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
/// 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");
}
use std::mem;
fn main(){
let xs = [i32; 5] = [1,2,3,4,5];
println!("{} {} {}", xs[0], xs.len(), mem::size_of_val(&xs));
}