[Rust] Slice and Vec metadata
struct VecMetadata {
first_elem_index: usize,
length: usize,
capacity: usize
}
struct SliceMetadata {
first_elem_index: usize,
length: usize
}
Slice is similar to Vec, but it is a slice of Vec. As notice in the defination, Slice doesn't have `capacity` property, because Slice always refer to existing reference in the memory.
let nums: Vec<u8> = vec![0,1,2,3];
let slice: &[u8] = &nums[0..2];
The important thing to notice is "Slice doesn't own the elements, just references them".
Full code of the Vec or String:
nums.as_slice()
strings.as_str()
Example:
fn main() {
let numbers = vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24];
let sum_of_nums = sum(numbers.as_slice());
let product_of_nums = product(numbers.as_slice());
let average_of_nums = average(numbers.as_slice());
println!("Sum of these numbers: {}", sum_of_nums);
println!("Product of these numbers: {}", product_of_nums);
println!("Average of these numbers: {}", average_of_nums);
}
fn sum(numbers: &[i64]) -> i64 {
let mut total = 0;
for num in numbers.iter() {
total += num;
}
total
}
fn product(numbers: &[i64]) -> i64 {
let mut total = 1;
for num in numbers.iter() {
total *= num;
}
total
}
fn average(numbers: &[i64]) -> i64 {
let length = numbers.len() as i64;
sum(numbers) / length
}
In the example we do: sum(numbers.as_slice());
calling `as_slice()` but actually it is not necessary, since we already define in function it takes slice, sum(numbers: &[i64])
, what we can do to simpify it:
fn main() {
let numbers = vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24];
let sum_of_nums = sum(&numbers);
let product_of_nums = product(&numbers);
let average_of_nums = average(&numbers);
println!("Sum of these numbers: {}", sum_of_nums);
println!("Product of these numbers: {}", product_of_nums);
println!("Average of these numbers: {}", average_of_nums);
}
Rust can convert Slice and Vec easily for us.