📜  Rust – 元组

📅  最后修改于: 2022-05-13 01:55:19.145000             🧑  作者: Mango

Rust – 元组

Rust 中的元组是一种有限异构复合数据类型,这意味着它可以一次存储多个值。 在元组中没有将元素添加到元组的内置方法。我们可以使用索引来获取元组的值,也不能使用 for 循环遍历元组。

Rust 中的元组使用小括号定义,如下所示:

Syntax: ("geeksforgeeks", 1, 'geek')

需要注意的是,元组在 Rust 中是一个序列。这意味着它的元素可以通过位置访问,也称为元组索引

示例 1:下面是在元组中获取值的 rust 程序。

Rust
// Rust program to get value from tuple
// using index
fn main() {
    let gfg = ("cp", "algo", "FAANG", "Data Structure");
   
    // complete tuple
    println!("complete tuple = {:?} ", gfg );
   
    // first value
    println!("at 0 index = {} ", gfg.0 );
   
    // second value
    println!("at 0 index = {} ", gfg.1 );
   
    // third value
    println!("at 0 index = {} ", gfg.2 );
   
    // fourth value
    println!("at 0 index = {} ", gfg.3 );
}


Rust
fn main() {
   
    // tuple with different types of values
    let gfg = ("cp", 10, "FAANG", 20);
    println!("complete tuple = {:?} ", gfg );
    println!("at 0 index = {} ", gfg.0 );
    println!("at 0 index = {} ", gfg.1 );
    println!("at 0 index = {} ", gfg.2 );
    println!("at 0 index = {} ", gfg.3 );
}


输出 :

complete tuple = ("cp", "algo", "FAANG", "Data Structure") 
at 0 index = cp 
at 0 index = algo 
at 0 index = FAANG 
at 0 index = Data Structure 

示例 2:这里我们将在元组中使用字符串和整数。

fn main() {
   
    // tuple with different types of values
    let gfg = ("cp", 10, "FAANG", 20);
    println!("complete tuple = {:?} ", gfg );
    println!("at 0 index = {} ", gfg.0 );
    println!("at 0 index = {} ", gfg.1 );
    println!("at 0 index = {} ", gfg.2 );
    println!("at 0 index = {} ", gfg.3 );
}

输出 :

complete tuple = ("cp", 10, "FAANG", 20) 
at 0 index = cp 
at 0 index = 10 
at 0 index = FAANG 
at 0 index = 20