let x = (); // similar to void in javascriptlet x = 5; // i32
let y = 2.5; // f64When working with numeric types, the types of numbers have to be the same.
Converting one data type to another.
let x = 255.0;
// the `as` keyword is used to convert one type to another
let y = x as u8 - 5;
println!("{}", y);If you want to change the value of a variable, it has to be mutable.
let mut x = 5; // mutable
x = 6;There are two different types of strings in Rust. Char and String.
let x: char = 'a'; // char
let y: &str = "hello" // string pointerlet x: (u8, &str) = (1 as u8, "hello"); // tupleThe items in a array must be the same data type.
let x: [u8; 5] = [1, 2, 3, 4, 5]; // array&[T]is a slice it doesn't own the data it points to.&mut [T]is a mutable slice it mutably borrows the data it points to.Box<[T]>a boxed slice.
let y: &[u8] = &[1, 2, 3, 4, 5]; // slice
// Items from an array can be sliced (from array section)
let x: &[u8] = &x[1..3]; // [2, 3]
let z: &[u8] = &x[1..=3]; // [2, 3, 4]
let ax: &[u8] = &x[..3]; // [1, 2, 3]
let az: &[u8] = &x[1..]; // [2, 3, 4, 5]fn get_full_name(first: &str, last: &str) -> String {
// Do not add ; at the end of a function to return a value
format!("{} {}", first, last)
}
// Optional syntax
fn get_full_name(first: &str, last: &str) -> String {
return format!("{} {}", first, last);
}To have the compiler skip the function, use the #[allow] attribute.
// This will turn off the warning in the compiler until
// you handle what you want to do later
#[allow(dead_code)]
fn get_full_name(first: &str, last: &str) -> String {
format!("{} {}", first, last)
}You can split code into a different module using the mod keyword.
file: src/helpers.rs
// `pub` makes the function public for other files
pub fn get_full_name(first: &str, last: &str) -> String {
format!("{} {}", first, last)
}file: src/main.rs
mod helpers;
fn main() {
let full_name = helpers::get_full_name("John", "Doe");
println!("{}", full_name);
}