句法
//Syntax1
let tuple_name:(data_type1,data_type2,data_type3) = (value1,value2,value3);
//Syntax2
let tuple_name = (value1,value2,value3);
Illustration
以下示例显示元组中的值。
fn main() {
let tuple:(i32,f64,u8) = (-325,4.9,22);
println!("{:?}",tuple);
}
println!("{:?}",tuple)的语法,不能使用在元组来显示值。这是因为元组是复合类型。使用println!("{:?}", tuple_name)语法打印元组中的值。
输出
Illustration
以下示例打印元组中的各个值。
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);
}
输出
integer is :-325
float is :4.9
unsigned integer is :2
Illustration
以下示例将元组作为参数传递给函数。元组按值传递给函数。
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);
}
输出
Inside print method
(110, true, 10.9)