-
-
Save ninedraft/1434d1bcba80e605e3fe6a811939209a to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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