[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.
分类:
Rust
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-04-08 [Tools] Kill the process running on port 8080
2020-04-08 [RxJS] Encapsulate complex imperative logic in a simple observable
2020-04-08 [RxJS] Remember previous value by using pairwise operator
2019-04-08 [Functional Programming] Build a Query function by using Crocks (Pred, Pair, Maybe)
2018-04-08 [Angular] ngx-formly (AKA angular-formly for Angular latest version)
2018-04-08 [React Router] Create a ProtectedRoute Component in React Router (setState callback to force update)
2017-04-08 [SCSS] Organize SCSS into Multiple Files with Partials