乐闻世界logo
搜索文章和话题

How to get a slice as an array in Rust?

1个答案

1

In Rust, converting a slice to an array requires ensuring that the slice's length exactly matches the target array's length. This is because arrays have fixed lengths at compile time, while slices' lengths are determined at runtime. Consequently, this conversion involves necessary safety checks.

Here is a concrete example demonstrating how to achieve this conversion:

rust
fn main() { let slice = [1, 2, 3, 4, 5]; if let Some(array) = slice.get(0..3) { let array: [i32; 3] = match array.try_into() { Ok(arr) => arr, Err(_) => { println!("Conversion failed: slice length mismatch"); return; } }; println!("Array: {:?}", array); } else { println!("Failed to obtain slice"); } }

In this example:

  1. First, define a slice slice.
  2. Use the .get(0..3) method to obtain a new slice containing the first three elements of the original slice.
  3. Use try_into() to attempt converting this slice into a fixed-length array of size 3. The try_into() method verifies that the slice's length matches the target array's length.
  4. If the lengths match, the conversion succeeds; otherwise, an error message is printed.

This approach is safe and prevents runtime failures because all checks are performed at compile time. Note that this method assumes the slice's length already matches the target array's length. If the lengths do not match, the try_into() method returns an error.

2024年8月7日 17:07 回复

你的答案