数组

数组是相同类型元素的集合。 可以使用 corelib 的 array::ArrayTrait 来定义可能的数组操作:

trait ArrayTrait<T> {
    fn new() -> Array<T>;
    fn append(ref self: Array<T>, value: T);
    fn pop_front(ref self: Array<T>) -> Option<T> nopanic;
    fn pop_front_consume(self: Array<T>) -> Option<(Array<T>, T)> nopanic;
    fn get(self: @Array<T>, index: usize) -> Option<Box<@T>>;
    fn at(self: @Array<T>, index: usize) -> @T;
    fn len(self: @Array<T>) -> usize;
    fn is_empty(self: @Array<T>) -> bool;
    fn span(self: @Array<T>) -> Span<T>;
}

例如:

fn array() -> bool {
    let mut arr = ArrayTrait::<u32>::new();
    arr.append(10);
    arr.append(20);
    arr.append(30);

    assert(arr.len() == 3, ‘array length should be 3’);

    let first_value = arr.pop_front().unwrap();
    assert(first_value == 10, ‘first value should match’);

    let second_value = *arr.at(0);
    assert(second_value == 20, ‘second value should match’);

    // 如果数组为空,返回 true;如果不为空,返回 false。
    arr.is_empty()
}
Last change: 2023-10-31, commit: 0d79abb