Rust 从入门到摔门而出门 - 元组

60 阅读1分钟

Rust 从入门到摔门而出门 - 元组

Rust 中元组, 通过()创建,可以()匹配值取出 或 通过·解构索引取出(从0开始)。

fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
    // 匹配模式
    let (x, y, z,) = tup;
    println!('x: {}', x);
    println!('y: {}', y);
    println!('z: {}', z);
    // 通过
    println!('tup.0: {}', tup.0);
    println!('tup.1: {}', tup.1);
    println!('tup.2: {}', tup.2);
}

在函数中运用:

// 函数返回一个元组
fn get_person() -> (i32, &'static str) {
    (30, "John")
}

// 函数接受一个元组作为参数
fn print_person(person: (i32, &'static str)) {
    println!("{} is {} years old.", person.1, person.0);
}

fn main() {
    // 调用函数并获取返回的元组
    let person = get_person();

    // 调用函数并传递一个元组作为参数
    print_person(person);
}

在这个示例中,get_person函数返回一个包含年龄和姓名的元组。然后我们调用 print_person 函数,并将 get_person返回的元组作为参数传递给它。print_person 函数接受一个元组参数,并打印出其中的值。