Arrays Versus Vec Fixed Sizes
Fixed-size arrays carry their length in the type, so a signature can force wrong lengths out at compile time, while Vec grows and both borrow as one slice.
Code
fn sum(values: &[i32]) -> i32 {
// &[i32] 同时接受数组与 Vec 的借用
values.iter().sum()
}
fn main() {
// 数组:定长,长度是类型的一部分
let readings: [i32; 4] = [10, 20, 30, 40];
println!("len is const: {}", readings.len());
// 长度在类型里,函数签名可强制编译期拒绝错误长度;但 zip 配对不校验长度
let labels = ["a", "b", "c", "d"];
let pairs: Vec<(&str, i32)> = labels
.iter()
.zip(readings.iter())
.map(|(label, value)| (*label, *value))
.collect();
println!("{pairs:?}");
// TryFrom<&[i32]> 把切片转回定长数组,长度不符会失败
let copied = <[i32; 4]>::try_from(readings.as_slice()).unwrap();
println!("round trip: {copied:?}");
let short = [1, 2, 3];
println!("3 into 4 fails: {}", <[i32; 4]>::try_from(short.as_slice()).is_err());
// 两者都能借给同一个 &[i32] 参数;Vec 可继续增长
let mut grown = readings.to_vec();
grown.push(50);
println!("sum fixed: {} sum grown: {}", sum(&readings), sum(&grown));
}How it works
Structurally, expect the functions sum and main and nothing else.
Applying it
The main signature reads fn sum(values: &[i32]) -> i32
Running the file prints labeled results such as len is const:, round trip:, 3 into 4 fails: — each operation’s effect is visible in the output.
Start the program and main runs sum one after another.
Statements that matter
.zip(readings.iter())
.map(|(label, value)| (*label, *value))
.collect();
values.iter().sum()
}
let copied = <[i32; 4]>::try_from(readings.as_slice()).unwrap();
Interactive Tools for This Topic
FAQ
- What does Arrays Versus Vec Fixed Sizes print when run?
- Running the file directly is enough — expect labeled output lines such as `len is const:`, `round trip:`, `3 into 4 fails:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.