Skip to content
On this page

原生类型4: exercises/primitive_types/primitive_types4.rs

题目

rust
// primitive_types4.rs
//
// Get a slice out of Array a where the ??? is so that the test passes.
//
// Execute `rustlings hint primitive_types4` or use the `hint` watch subcommand
// for a hint.

// I AM NOT DONE

#[test]
fn slice_out_of_array() {
    let a = [1, 2, 3, 4, 5];

    let nice_slice = ???

    assert_eq!([2, 3, 4], nice_slice)
}

从数组中获取一个切片,以便程序编译通过。

题目解析

我们可以参考其他类型切片内容介绍的,直接获取数组切片。

只是需要注意assert_eq!([2, 3, 4], nice_slice),我们只需要取索引为1-4的元素即可:

rust
#[test]
fn slice_out_of_array() {
    let a = [1, 2, 3, 4, 5];

    let nice_slice = ??? 
    let nice_slice = &a[1..4]; 

    assert_eq!([2, 3, 4], nice_slice)
}

笔记

  • slice 允许你引用集合中一段连续的元素序列,而不用引用整个集合。
  • slice 是一类引用,所以它没有所有权。

参考资料

Powered by VitePress