Learn Rust Programming Language for Beginner
2 min readDec 26, 2023
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
format!
: write formatted text to string. To see the ouput offormat!
, you need to assign it in variable and the use print! orprintln!
.print!
: same asformat!
but the text is printed to the console(io::stdout).println!
: same asprint!
but a new line is appendedeprint!
: same asprint!
but text is printed to the standard error(io::stderr)eprintln!
: same aseprint!
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