Day 1:向量 Vector
學習目標
- 建立、讀取、修改 Vec
- 理解所有權與索引操作的關係
- 用 get() 安全地取值
今日重點
建立向量
let mut v: Vec<i32> = Vec::new();
v.push(5); v.push(6); v.push(7);
let v2 = vec![1, 2, 3, 4, 5]; // 使用巨集(推薦)
讀取元素
let third: &i32 = &v[2]; // 索引,越界會 panic
match v.get(2) { // get() 回傳 Option,安全
Some(th) => println!("{}", th),
None => println!("no element"),
}
v[2] vs v.get(2):前者越界直接當機,後者回傳 None 由你處理。
迭代
for i in &v { // 借用
println!("{}", i);
}
for i in &mut v { // 可變借用
*i += 1;
}
for i in v { // 取得所有權(之後 v 不能再用)
println!("{}", i);
}
練習
fn main() {
let mut scores = vec![90, 75, 88, 62];
scores.push(95);
// 1. 用 get() 安全取 scores[10]
match scores.get(10) {
Some(s) => println!("{}", s),
None => println!("沒有這個元素"),
}
// 2. 把每個分數 +5
for s in &mut scores { *s += 5; }
println!("{:?}", scores);
}
自我檢查
深入連結