diff options
| author | Matthias Krüger <matthias.krueger@famsik.de> | 2022-09-17 19:27:05 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-09-17 19:27:05 +0200 |
| commit | 00d88bdb2c59c4d40add0aa36ba1013d06afd32f (patch) | |
| tree | bafe288b41347b881e2cf8e607135d61a586a1f3 /library/std/src | |
| parent | 48de123d7a0753026c362a06109f9a9cebde2a2a (diff) | |
| parent | 705a7667c5e14c7155145041ca2abe45c2863ea7 (diff) | |
| download | rust-00d88bdb2c59c4d40add0aa36ba1013d06afd32f.tar.gz rust-00d88bdb2c59c4d40add0aa36ba1013d06afd32f.zip | |
Rollup merge of #101672 - idigdoug:array_try_into, r=Mark-Simulacrum
array docs - advertise how to get array from slice On my first Rust project, I spent more time than I care to admit figuring out how to efficiently get an array from a slice. Update the array documentation to explain this a bit more clearly. (As a side note, it's a bit unfortunate that get-array-from-slice is only available via trait since that means it can't be used from const functions yet.)
Diffstat (limited to 'library/std/src')
| -rw-r--r-- | library/std/src/primitive_docs.rs | 23 |
1 files changed, 22 insertions, 1 deletions
diff --git a/library/std/src/primitive_docs.rs b/library/std/src/primitive_docs.rs index 242f44ade8a..331714a993c 100644 --- a/library/std/src/primitive_docs.rs +++ b/library/std/src/primitive_docs.rs @@ -611,7 +611,19 @@ mod prim_pointer {} /// /// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on /// an array. Indeed, this provides most of the API for working with arrays. -/// Slices have a dynamic size and do not coerce to arrays. +/// +/// Slices have a dynamic size and do not coerce to arrays. Instead, use +/// `slice.try_into().unwrap()` or `<ArrayType>::try_from(slice).unwrap()`. +/// +/// Array's `try_from(slice)` implementations (and the corresponding `slice.try_into()` +/// array implementations) succeed if the input slice length is the same as the result +/// array length. They optimize especially well when the optimizer can easily determine +/// the slice length, e.g. `<[u8; 4]>::try_from(&slice[4..8]).unwrap()`. Array implements +/// [TryFrom](crate::convert::TryFrom) returning: +/// +/// - `[T; N]` copies from the slice's elements +/// - `&[T; N]` references the original slice's elements +/// - `&mut [T; N]` references the original slice's elements /// /// You can move elements out of an array with a [slice pattern]. If you want /// one element, see [`mem::replace`]. @@ -640,6 +652,15 @@ mod prim_pointer {} /// for x in &array { } /// ``` /// +/// You can use `<ArrayType>::try_from(slice)` or `slice.try_into()` to get an array from +/// a slice: +/// +/// ``` +/// let bytes: [u8; 3] = [1, 0, 2]; +/// assert_eq!(1, u16::from_le_bytes(<[u8; 2]>::try_from(&bytes[0..2]).unwrap())); +/// assert_eq!(512, u16::from_le_bytes(bytes[1..3].try_into().unwrap())); +/// ``` +/// /// You can use a [slice pattern] to move elements out of an array: /// /// ``` |
