元组和数组

元组和数组是我们见过的第一个 “复合”类型。数组的所有元素具有相同的类型,而元组可以适应不同的类型。这两种类型的大小在编译时是固定的。

类型字面量
数组(Arrays)[T; N][20, 30, 40], [0; 3]
元组(Tuples)(), (T,), (T1, T2), …(), ('x',), ('x', 1.2), …

数组的赋值和访问操作:

fn main() {
    let mut a: [i8; 10] = [42; 10];
    a[5] = 0;
    println!("a: {a:?}");
}

元组的赋值和访问操作:

fn main() {
    let t: (i8, bool) = (7, true);
    println!("t.0: {}", t.0);
    println!("t.1: {}", t.1);
}
This slide should take about 10 minutes.

关键点:

数组:

  • A value of the array type [T; N] holds N (a compile-time constant) elements of the same type T. Note that the length of the array is part of its type, which means that [u8; 3] and [u8; 4] are considered two different types. Slices, which have a size determined at runtime, are covered later.

  • 请尝试访问出界数组元素。系统会在运行时检查数组访问。Rust 通常会通过优化消除这些检查,以及使用不安全的 Rust 来避免这些检查。

  • 我们可以使用字面量来为数组赋值。

  • The println! macro asks for the debug implementation with the ? format parameter: {} gives the default output, {:?} gives the debug output. Types such as integers and strings implement the default output, but arrays only implement the debug output. This means that we must use debug output here.

  • 添加 #,比如 {a:#?},会输出“美观打印(pretty printing)” 格式,这种格式可能会更加易读。

元组:

  • 和数组一样,元组也具有固定的长度。

  • 元组将不同类型的值组成一个复合类型。

  • 元组中的字段可以通过英文句号加上值的下标进行访问比如:t.0, t.1

  • The empty tuple () is also known as the “unit type”. It is both a type, and the only valid value of that type — that is to say both the type and its value are expressed as (). It is used to indicate, for example, that a function or expression has no return value, as we’ll see in a future slide.

    • You can think of it as void that can be familiar to you from other programming languages.