fn main() {
let mut v = Vec::new();
v.push(10);
v.push(20);
v.push(30);
println!("v = {:?}", v);
}
3. 讀取元素
rust
fn main() {
let v = vec![100, 200, 300];
// 索引讀取 (會 panic 如果超出範圍)
println!("第一個元素: {}", v[0]);
// 使用 get 回傳 Option<T>,安全取元素
match v.get(10) {
Some(value) => println!("第十一個元素是 {}", value),
None => println!("沒有第十一個元素"),
}
}
4. 修改元素 (可變借用)
rust
fn main() {
let mut v = vec![1, 2, 3];
if let Some(x) = v.get_mut(1) {
*x = 20; // 修改第二個元素
}
println!("{:?}", v);
}
5. 刪除元素
rust
fn main() {
let mut v = vec![1, 2, 3, 4];
// pop 刪除並回傳最後一個元素
let last = v.pop();
println!("刪除的最後元素: {:?}", last);
println!("v 現在 {:?}", v);
// 移除特定索引元素 (2號索引)
let removed = v.remove(1); // 移除索引 1 (第二個元素)
println!("刪除的元素: {}", removed);
println!("v 現在 {:?}", v);
}
6. 遍歷 Vec
rust
fn main() {
let v = vec![10, 20, 30];
// 只讀取
for val in &v {
println!("值是 {}", val);
}
// 可修改元素(需可變 Vec)
let mut v = vec![1, 2, 3];
for val in &mut v {
*val *= 2; // 每個元素乘以 2
}
println!("修改後 v: {:?}", v);
}
7. 清空 Vec
rust
fn main() {
let mut v = vec![1, 2, 3];
v.clear();
println!("清空後 v 的長度為 {}", v.len());
}
使用毛毯實現(blanket implementation)定義一個 Average trait,並為所有實作了某些條件的型別(例如實作了 Iterator 且元素為可計算平均的型別)提供通用實現。
示範:為所有迭代出可加總元素的 Iterator 實作 Average trait
1. 定義 Average trait
rust
trait Average {
type Output;
fn average(&mut self) -> Option<Self::Output>;
}
average 功能是計算平均值,可能沒東西(空集合),所以用 Option。
Self::Output 代表回傳的數值型別。
2. 毛毯實作給所有 Iterator 其元素是可相加並可除(Add + Div + Copy + From<u8>)
rust
use std::ops::{Add, Div};
impl<I, T> Average for I
where
I: Iterator<Item = T>,
T: Add<Output = T> + Div<Output = T> + Copy + From<u8>,
{
type Output = T;
fn average(&mut self) -> Option<T> {
let mut count = 0u32;
let mut sum = None;
for value in self {
count += 1;
sum = Some(match sum {
Some(acc) => acc + value,
None => value,
});
}
sum.map(|total| total / T::from(count))
}
}
3. 測試 Average trait
rust
fn main() {
let numbers = vec![10, 20, 30, 40, 50];
// 使用毛毯實作的 `average`,因為 Vec<T> 可迭代
let mut iter = numbers.iter().copied(); // Iterator<Item=i32>
match iter.average() {
Some(avg) => println!("平均值是 {}", avg),
None => println!("沒有元素,無法算平均"),
}
}
Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project)
error[E0119]: conflicting implementations of trait SayHello for type &str
--> src\main.rs:16:1
|
9 | impl<T: Display> SayHello for T {
| ------------------------------- first implementation here
...
16 | impl SayHello for &str {
| ^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for &str
error[E0119]: conflicting implementations of trait SayHello for type i32
--> src\main.rs:23:1
|
9 | impl<T: Display> SayHello for T {
| ------------------------------- first implementation here
...
23 | impl SayHello for i32 {
| ^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for i32
error[E0119]: conflicting implementations of trait SayHello for type bool
--> src\main.rs:30:1
|
9 | impl<T: Display> SayHello for T {
| ------------------------------- first implementation here
...
30 | impl SayHello for bool {
| ^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for bool
error[E0119]: conflicting implementations of trait SayHello for type Vec<_>
--> src\main.rs:41:1
|
9 | impl<T: Display> SayHello for T {
| ------------------------------- first implementation here
...
41 | impl<T: Display> SayHello for Vec {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for Vec<_>
|
= note: upstream crates may add a new impl of trait std::fmt::Display for type std::vec::Vec<_> in future versions
For more information about this error, try rustc --explain E0119.
這裡提供一版加強版的範例,利用 match 處理 read_line 的結果,並確保名字非空,也避免了空字串導致的問題,整體讓程式更健壯且不會 panic。
rust
use std::io;
fn main() {
println!("嗨!請輸入你的名字:");
let mut name = String::new();
let result = io::stdin().read_line(&mut name);
match result {
Ok(_) => {
let name = name.trim();
if name.is_empty() {
println!("你沒有輸入名字,請再試一次!");
} else {
println!("歡迎你,{}!很高興認識你!", name);
println!("你的名字有 {} 個字元!", name.chars().count());
}
}
Err(e) => {
println!("讀取輸入時發生錯誤:{}", e);
}
}
}