In the last post, I discussed about scalar datatypes in rust | Divyansh Rai

Shared on Rust

editor-img
Divyansh Rai
Jul 21, 2022
shared in

In the last post, I discussed about scalar datatypes in rust https://fifo.im/p/pwp8i1js94g0 Today, I will throw some light on compound types:

Compound types can group multiple values into one type. Rust has two primitive compound types: tuples and arrays.

# Tuple Type A tuple is a general way of grouping together a number of values with a variety of types into one compound type. Tuples have a fixed length: once declared, they cannot grow or shrink in size. Example: fn main() { let tup: (i32, f64, u8) = (500, 6.4, 1); }

The variable tup binds to the entire tuple, because a tuple is considered a single compound element. To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value, like this: fn main() { let tup = (500, 6.4, 1); let (x, y, z) = tup; println!("The value of y is: {y}"); }

We can also access a tuple element directly by using a period (.) followed by the index of the value we want to access. For example: fn main() { let x: (i32, f64, u8) = (500, 6.4, 1); let five_hundred = x.0; let six_point_four = x.1; let one = x.2; }

# Array Type Another way to have a collection of multiple values is with an array. Unlike a tuple, every element of an array must have the same type. Unlike arrays in some other languages, arrays in Rust have a fixed length. We write the values in an array as a comma-separated list inside square brackets: fn main() { let a = [1, 2, 3, 4, 5]; }


Tagged users
editor-img
Rajat
@28-mace-windu
I don't know. I'm pretty much done with everythinghh!
Checkout related posts on: