Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active January 6, 2024 13:12
Show Gist options
  • Save max-itzpapalotl/11379c5b70498812a2c342eca1fadc8e to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/11379c5b70498812a2c342eca1fadc8e to your computer and use it in GitHub Desktop.
3. Basic data types in Rust

3. Basic data types in Rust

  • integers, signed and unsigned
  • floats
  • bool
  • char
  • std::mem::size_of
  • String and &str
  • arithmetic: only same types
  • casting with "as"
  • integer overflow

Integers

fn main() {
    let u : u64 = 123;
    let i : i64 = -123;
    println!("{} {}", u, i);
}

Floats

fn main() {
    let d : f64 = 1.23;
    let f : f32 = 4.56;
    println!("{} {}", d, f);
}

Boolean

fn main() {
    let b1 : bool = true;
    let b2 : bool = false;
    println!("{} {}", b1, b2);
}

Characters

fn main() {
    let c : char = 'a';
    println!("{} {}", c, std::mem::size_of::<char>());
}

Machine dependent integer

fn main() {
    let i : usize = 123;
    println!("{} {}", i, std::mem::size_of::<usize>());
}

Strings and string slices

fn main() {
    let s : String = "abc".to_string();
    let t = "xyz";
    println!("{} {}", s, t);
}

Arithmetic

fn main() {
    let a : u64 = 123;
    let b : u64 = 456;
    println!("{} {} {}", a, b, a+b);
}
fn main() {
    let a : u64 = 123;
    let b : u32 = 456;
    println!("{} {} {}", a, b, a + b as u64);
}

Integer overflow

fn main() {
    let a : u8 = 123;
    let b : u8 = 200;
    println!("{} {} {}", a, b, a + b);
}
cargo run
cargo run --release

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment