Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active January 6, 2024 13:13
Show Gist options
  • Save max-itzpapalotl/709356dbed7da1e3bf32bd91a16a0a76 to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/709356dbed7da1e3bf32bd91a16a0a76 to your computer and use it in GitHub Desktop.
5. Compound types: tuples and arrays

5. Compound types: tuples and arrays

  • Tuple type and syntax of tuples
  • Printing
  • Tuples as argument types, access to components
  • Tuples as return values
  • Destructuring tuples
  • Array type and array syntax
  • Printing
  • Bounds checking at compile time
  • Bounds checking at run time
  • Array slices
  • Bounds checking the same

Tuples

fn f(a : (u64, u32)) -> (u32, u64) {
    (a.1, a.0)
}

fn main() {
    let a : (u64, u32) = (1, 2);
    let b : (i32, String) = (17, "abc".to_string());
    println!("{:?} {:?}", a, b);
    println!("{:?} {}", f(a), b.1);
    let (c, d) = f(a);
    println!("{} {}", c, d);
}

Arrays

fn main() {
    let a : [u16; 3] = [1, 2, 3];
    let args : Vec<String> = std::env::args().collect();
    println!("{:?}", args);
    let b = usize::from_str_radix(&args[1], 10).unwrap();
    println!("{}", a[b]);
}

Slicing works as for strings:

fn main() {
    let a : [u16; 3] = [1, 2, 3];
    let args : Vec<String> = std::env::args().collect();
    println!("{:?}", args);
    let b = usize::from_str_radix(&args[1], 10).unwrap();
    println!("{}", a[b]);
    let c = &args[1..3];
    println!("{:?}", c);
}

Even mutable slices are allowed:

fn main() {
    let a : [u16; 3] = [1, 2, 3];
    let mut args : Vec<String> = std::env::args().collect();
    println!("{:?}", args);
    let b = usize::from_str_radix(&args[1], 10).unwrap();
    println!("{}", a[b]);
    let c = &mut args[1..3];
    c[0] = "abc".to_string();
    println!("{:?}", c);
    println!("{:?}", args);
}

References:

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