Basic Operations

introduction

  • difference between macros and functions: macros have the ! symbol

  • they behave similarly

  • a macro can take an arbitrary number of arguments, cant do that if it were a regular function

fn main() {
    println!("Hello, world!");
}
  • if statements dont need to have parentheses

fn main() {
  let x = 42; 

  if x == 42 {
    println!("x is 42"); 
  } else if  x % 2 == 0 {
    println!("x is even"); 
  } else {
    println!("x is odd"); 
  }
}
  • if statements can have return values

  • rust makes a distinction between string literals and string types

  • println statement only accepts string literals

  • for loops:

  • fizzbuzz

  • integers and floats

  • default integer type is the signed i32, can use bigger types like i64 or i128 , or unsigned u128 if we dont need negative values

  • two types of floats, f32 and f64

  • all integer sizes supported by rust: 8 16 32 64 128

  • overflows and underflows

  • we can return values without using the return keyword, if the last value in the function does not end with a semicolon

  • if we want to do an early return, we would have to use the return statement

  • this still compiles because the final return value originates from the if statement

    • will not work if we add semicolons to after the x and y values

  • vectors are like lists/arrays in other languages

  • have to use a different format string if we want to print a vector

  • loop through vector length and print elements

  • popping value from Vector may return Option<i32>

  • options are an important part of why is rust is safer than other languages, because when you pop an item out of an array, there is no guarantee what type it is

  • generally rust returns options when there’s a possibility that an operation might fail

  • forces user to deal with an invalid value at compile time

  • an option can be one of two types: some and none

    • none - returns when we would usually expect null pointers or exceptions

    • some - returns when succeeds

  • cannot treat options like the value they contain, e.g. cannot add an integer to an option

  • rust does not always produce an option, will panic in some other situations, for example when accessing an array out of bounds

  • can convert to another form to return an option instead

  • convert Some(3) into a regular 3

Last updated