pub trait ArrayAsRef<'a>: Array{
type AsRef: Array<Item = &'a <Self as Array>::Item>;
type AsMut: Array<Item = &'a mut <Self as Array>::Item>;
// Required methods
fn as_ref_array(&'a self) -> Self::AsRef;
fn as_mut_array(&'a mut self) -> Self::AsMut;
}
Expand description
Trait for conversation between &[T; N]
and [&T; N]
(or &mut [T; N]
and
[&mut T; N]
)
Required Associated Types§
Required Methods§
Sourcefn as_ref_array(&'a self) -> Self::AsRef
fn as_ref_array(&'a self) -> Self::AsRef
Convert &self
to [&T; N]
(where T = Self::Item, N = Self::Size
)
§Examples
use arraylib::ArrayAsRef;
let arr = [0, 1, 2, 3];
let ref_arr = arr.as_ref_array();
assert_eq!(ref_arr, [&0, &1, &2, &3]);
assert_eq!(arr, [0, 1, 2, 3]);
use arraylib::{ArrayAsRef, ArrayExt};
// Don't do like this, it's just an example
fn index_of<A>(a: &A, x: A::Item) -> Option<usize>
where
for<'a> A: ArrayAsRef<'a>,
A::Item: PartialEq,
{
a.as_ref_array()
.iter_move()
.enumerate()
.find(|&(_, it)| it == &x)
.map(|(idx, _)| idx)
}
let arr = [-2, 1, -1, 2];
assert_eq!(index_of(&arr, 1), Some(1));
assert_eq!(index_of(&arr, 2), Some(3));
assert_eq!(index_of(&arr, 0), None);
NOTE: it’s nighly recommended to use iterators when you need to
perform more that one operation (e.g. map + as_ref) because iterators
are lazy and ArrayAsRef
isn’t.
See also: as_mut_array
Sourcefn as_mut_array(&'a mut self) -> Self::AsMut
fn as_mut_array(&'a mut self) -> Self::AsMut
Convert &mut self
to [&mut T; N]
(where T = Self::Item, N = Self::Size
)
§Examples
use arraylib::ArrayAsRef;
let mut arr = [0, 1, 2, 3];
let ref_arr = arr.as_mut_array();
assert_eq!(ref_arr, [&mut 0, &mut 1, &mut 2, &mut 3]);
assert_eq!(arr, [0, 1, 2, 3]);
use arraylib::{ArrayAsRef, ArrayExt};
// Don't do like this, it's just an example
fn find_and_replace<A>(a: &mut A, find: &A::Item, replace: A::Item) -> A::Item
where
for<'a> A: ArrayAsRef<'a>,
A::Item: PartialEq,
{
let mut x = a.as_mut_array().iter_move().find(|it| it == &find);
match x {
Some(ref mut inner) => core::mem::replace(inner, replace),
None => replace,
}
}
let mut arr = [-2, 1, -1, 2];
assert_eq!(find_and_replace(&mut arr, &1, 8), 1);
assert_eq!(arr, [-2, 8, -1, 2]);
NOTE: it’s nighly recommended to use iterators when you need to
perform more that one operation (e.g. map + as_ref) because iterators
are lazy and ArrayAsRef
isn’t.
See also: as_ref_array
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.