| Definition |
|
tuple is a compound data type a scalar type can store only one type of data compound types can store more than one value at a time can be of different types have a fixed length, cannot grow or shrink in size zero-based index |
| Syntax |
two ways to create a tuple
let tuple_name:(data_type1,data_type2,data_type3) = (value1,value2,value3); let tuple_name = (value1,value2,value3);example fn main() {
let tuple:(i32,f64,u8) = (-325,4.9,22);
println!("{:?}",tuple);
}
output
(-325, 4.9, 22)the println!("{ }",tuple) syntax cannot be used to display values in a tuple use the println!("{:?}", tuple_name) syntax to print values in a tuple example prints individual values in a tuple fn main() {
let tuple:(i32,f64,u8) = (-325,4.9,22);
println!("integer is :{:?}",tuple.0);
println!("float is :{:?}",tuple.1);
println!("unsigned integer is :{:?}",tuple.2);
}
output
integer is :-325 float is :4.9 unsigned integer is :2example passes a tuple as parameter to a function tuples are passed by value to functions fn main(){
let b:(i32,bool,f64) = (110,true,10.9);
print(b);
}
//pass the tuple as a parameter
fn print(x:(i32,bool,f64)){
println!("Inside print method");
println!("{:?}",x);
}
|
| Destructing |
|
destructing assignment is a feature of rust to unpack the values of a tuple achieved by assigning a tuple to distinct variables fn main(){
let b:(i32,bool,f64) = (30,true,7.9);
print(b);
}
fn print(x:(i32,bool,f64)){
println!("Inside print method");
let (age,is_male,cgpa) = x; //assigns a tuple to distinct variables
println!("Age is {} , isMale? {},cgpa is
{}",age,is_male,cgpa);
}
variable x is a tuple which is assigned to the let statementeach variable - age, is_male and cgpa will contain the corresponding values in a tuple output Inside print method Age is 30 , isMale? true,cgpa is 7.9 |