Learning Rust with C basics
fn main() {
println!("Hello, World!");
}
fn
keyword is used to declare a function
main
function is the entry point of the program
!
indicates that println
is a macro, not a function
println!
is a macro that prints text to the console
let x = 5;
let y: i32 = 10;
let mut z = 15.0;
let y = "Hello, World!"; // shadowing
- using
let
to declare a variable
- using
:
after the variable name to specify the type of the variable (optional)
- variables are immutable by default
- using
mut
to make a variable mutable
- variables can be shadowed
let x = 0b1101_1010;
let c = '😆';
let t = (1, 2.0, "three");
// same with let t: (i32, f32, &str) = (1, 2.0, "three");
let a = [1, 2, 3, 4, 5];
_
can be used as a visual separator for large numbers
char
type represents a single Unicode character, which is 4 bytes in size
tuple
type can be used to group multiple values of different types
array
type has a fixed length and all elements must have the same type
index out of bounds
error will be thrown at runtime if the index is out of bounds
fn addi32(x: i32, y: i32) -> i32 {
x + y
}
fn main() {
let x = 5;
let y = 10;
let z = addi32(x, y);
println!("{} + {} = {}", x, y, z);
}
- functions are declared using the
fn
keyword
- function's parameters must have type annotations, eg.
x: i32
- function's return type using annotations, eg.
-> i32
- statements not returning a value,
x=y=5;
is not allowed
- expressions do not include ending semicolons,
x+y
is an expression, x+y;
is a statement