Created
August 10, 2017 05:18
-
-
Save shawnsmithdev/12643cefabefa0366ef15708a4b920f2 to your computer and use it in GitHub Desktop.
Rust slices
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
// https://stackoverflow.com/questions/28219231/how-to-idiomatically-copy-a-slice | |
fn copy_slice<T: Copy>(src: &[T], dst: &mut [T]) -> usize { | |
let mut c = 0; | |
for (d, s) in dst.iter_mut().zip(src.iter()) { | |
*d = *s; | |
c += 1; | |
} | |
c | |
} | |
fn main() { | |
println!("Hello, 世界"); | |
let x: [u8; 5] = [5, 4, 3, 2, 1]; | |
let mut y: [u8; 5] = [0; 5]; | |
println!("x:{:?}", x); | |
println!("y:{:?}", y); | |
copy_slice(& x, &mut y); | |
y.sort(); | |
println!("x:{:?}", x); | |
println!("y:{:?}", y); | |
let z = vec![4u8, 1, 5, 3, 2]; | |
println!("z:{:?}", z); | |
let mut a = vec![0u8; z.len()]; | |
copy_slice(& z, &mut a); | |
println!("a:{:?}", a); | |
a.sort(); | |
println!("a:{:?}", a); | |
// Hello, 世界 | |
// x:[5, 4, 3, 2, 1] | |
// y:[0, 0, 0, 0, 0] | |
// x:[5, 4, 3, 2, 1] | |
// y:[1, 2, 3, 4, 5] | |
// z:[4, 1, 5, 3, 2] | |
// a:[4, 1, 5, 3, 2] | |
// a:[1, 2, 3, 4, 5] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment