Skip to content

Instantly share code, notes, and snippets.

@ninedraft
Forked from anonymous/playground.rs
Created May 29, 2017 08:51
Show Gist options
  • Save ninedraft/1434d1bcba80e605e3fe6a811939209a to your computer and use it in GitHub Desktop.
Save ninedraft/1434d1bcba80e605e3fe6a811939209a to your computer and use it in GitHub Desktop.
Shared via Rust Playground
use std::convert::AsMut;
fn clone_into_array<A, T>(slice: &[T]) -> Option<A>
where A: Sized + Default + AsMut<[T]>,
T: Clone
{
let mut arr = Default::default();
{
let mut_arr = <A as AsMut<[T]>>::as_mut(&mut arr);
let arr_len = mut_arr.len();
if arr_len > slice.len() {
return None
}
mut_arr.clone_from_slice(&slice[..arr_len]);
}
Some(arr)
}
fn main() {
let a: Option<[u8; 4]> = clone_into_array(&[1, 4, 5, 59, 98]);
println!("{:?}", a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment