let v = vec![1, 2, 3, 4, 5, 6];
let filtered_doubled: Vec<_> = v.iter()
.filter(|&&x| x % 2 == 0) // 過濾偶數
.map(|x| x * 2) // 乘以 2
.collect();
println!("{:?}", filtered_doubled); // [4, 8, 12]
2. 使用 fold 覆蓋累加求和
let v = vec![1, 2, 3, 4];
let sum = v.iter().fold(0, |acc, &x| acc + x);
println!("sum = {}", sum); // sum = 10
3. 使用 enumerate 取得索引和值
let v = vec!["a", "b", "c"];
for (i, val) in v.iter().enumerate() {
println!("index: {}, value: {}", i, val);
}
// 輸出:
// index: 0, value: a
// index: 1, value: b
// index: 2, value: c
let temps = vec![20, 22, 23, 21, 20, 19, 18];
for window in temps.windows(3) {
let avg: f64 = window.iter().sum::<i32>() as f64 / window.len() as f64;
println!("3 天平均溫度: {:.2}", avg);
}
error[E0308]: mismatched types
--> src\main.rs:38:9
|
36 | let mut texture = Texture::from_image(
| ------------------- arguments to this function are incorrect
37 | &mut texture_context,
38 | &buffer,
| ^^^^^^^ expected ImageBuffer<Rgba<u8>, Vec<u8>>, found a different ImageBuffer<Rgba<u8>, Vec<u8>>
|
note: two different versions of crate image are being used; two types coming from two different versions of the same crate are different types even if they look the same
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\image-0.24.9\src\buffer.rs:656:1
|
656 | pub struct ImageBuffer<P: Pixel, Container> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is the found type ImageBuffer
|
::: C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\image-0.25.6\src\buffer.rs:656:1
|
656 | pub struct ImageBuffer<P: Pixel, Container> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is the expected type image::buffer_::ImageBuffer
|
::: src\main.rs:1:1
|
1 | extern crate piston_window;
| --------------------------- one version of crate image used here, as a dependency of crate gfx_texture
2 | extern crate rand;
3 | extern crate image;
| ------------------- one version of crate image used here, as a direct dependency of the current crate
= help: you can use cargo tree to explore your dependency tree
note: associated function defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston-gfx_texture-0.45.0\src\lib.rs:147:12
|
147 | pub fn from_image<F, C>(
| ^^^^^^^^^^
error[E0308]: mismatched types
--> src\main.rs:72:46
|
72 | texture.update(&mut texture_context, &buffer).unwrap();
| ------ ^^^^^^^ expected ImageBuffer<Rgba<u8>, Vec<u8>>, found a different ImageBuffer<Rgba<u8>, Vec<u8>>
| |
| arguments to this method are incorrect
|
note: two different versions of crate image are being used; two types coming from two different versions of the same crate are different types even if they look the same
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\image-0.24.9\src\buffer.rs:656:1
|
656 | pub struct ImageBuffer<P: Pixel, Container> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is the found type ImageBuffer
|
::: C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\image-0.25.6\src\buffer.rs:656:1
|
656 | pub struct ImageBuffer<P: Pixel, Container> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is the expected type image::buffer_::ImageBuffer
|
::: src\main.rs:1:1
|
1 | extern crate piston_window;
| --------------------------- one version of crate image used here, as a dependency of crate gfx_texture
2 | extern crate rand;
3 | extern crate image;
| ------------------- one version of crate image used here, as a direct dependency of the current crate
= help: you can use cargo tree to explore your dependency tree
note: method defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston-gfx_texture-0.45.0\src\lib.rs:181:12
|
181 | pub fn update<F, C>(
| ^^^^^^
For more information about this error, try rustc --explain E0308.
error: could not compile my_project (bin "my_project") due to 2 previous errors
use piston_window::*;
use piston_window::Texture;
use piston_window::TextureSettings;
// 用 piston_window re-export 的 image crate
use piston_window::image::{ImageBuffer, Rgba};
extern crate piston_window;
extern crate rand;
extern crate image;
use piston_window::*;
use rand::Rng;
use image::{ImageBuffer, Rgba}; // 直接用 image crate
fn main() {
let width = 320;
let height = 240;
let mut window: PistonWindow =
WindowSettings::new("復古電視雜訊", [width, height])
.exit_on_esc(true)
.build()
.unwrap();
// 背景底色
let background_color = [0.1, 0.2, 0.3, 1.0];
// 建立 ImageBuffer
let mut buffer: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_pixel(
width,
height,
Rgba([
(background_color[0] * 255.0) as u8,
(background_color[1] * 255.0) as u8,
(background_color[2] * 255.0) as u8,
255,
]),
);
let mut texture_context = window.create_texture_context();
let mut texture = Texture::from_image(
&mut texture_context,
&buffer,
&TextureSettings::new(),
)
.unwrap();
let mut noise_enabled = false;
while let Some(event) = window.next() {
if let Some(Button::Keyboard(key)) = event.press_args() {
if key == Key::Space {
noise_enabled = !noise_enabled;
println!("Noise enabled: {}", noise_enabled);
}
}
if noise_enabled {
for (_, _, pixel) in buffer.enumerate_pixels_mut() {
let noise = rand::thread_rng().gen_range(0..=255);
*pixel = Rgba([noise, noise, noise, 255]);
}
} else {
for (_, _, pixel) in buffer.enumerate_pixels_mut() {
*pixel = Rgba([
(background_color[0] * 255.0) as u8,
(background_color[1] * 255.0) as u8,
(background_color[2] * 255.0) as u8,
255,
]);
}
}
texture.update(&mut texture_context, &buffer).unwrap();
window.draw_2d(&event, |context, graphics, device| {
clear([1.0; 4], graphics);
image(&texture, context.transform, graphics);
texture_context.encoder.flush(device);
});
}
}
4. 建議你用以下指令確認 image 版本衝突:
cargo tree -p image
如果看到有多個版本,請用
[patch.crates-io]
image = "=0.24.9"
或同版本號,統一所有套件使用同一版。
小結
ImageBuffer、Rgba 都是 image crate 的型別,要直接 use image::{...}。
pipston_window 並不 re-export image。
確保 image crate 版本和 piston_window 相容,避免版本衝突。
有任何後續問題歡迎再提問!祝你順利。
error[E0432]: unresolved imports piston_window::image::ImageBuffer, piston_window::image::Rgba
--> src\main.rs:8:28
|
8 | use piston_window::image::{ImageBuffer, Rgba};
| ^^^^^^^^^^^ ^^^^ no Rgba in image
| |
| no ImageBuffer in image
= help: consider importing this struct instead:
::image::ImageBuffer
= help: consider importing one of these items instead:
::image::Rgba
conrod_core::Color::Rgba
conrod_core::color::Rgba
For more information about this error, try rustc --explain E0432.
error: could not compile my_project (bin "my_project") due to 1 previous error
PS C:\Users\fer52\mynewcargo\my_project> cargo run
Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project)
error[E0308]: mismatched types
--> src\main.rs:38:9
|
36 | let mut texture = Texture::from_image(
| ------------------- arguments to this function are incorrect
37 | &mut texture_context,
38 | &buffer,
| ^^^^^^^ expected ImageBuffer<Rgba<u8>, Vec<u8>>, found a different ImageBuffer<Rgba<u8>, Vec<u8>>
|
note: two different versions of crate image are being used; two types coming from two different versions of the same crate are different types even if they look the same
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\image-0.24.9\src\buffer.rs:656:1
|
656 | pub struct ImageBuffer<P: Pixel, Container> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is the found type ImageBuffer
|
::: C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\image-0.25.6\src\buffer.rs:656:1
|
656 | pub struct ImageBuffer<P: Pixel, Container> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is the expected type image::buffer_::ImageBuffer
|
::: src\main.rs:1:1
|
1 | extern crate piston_window;
| --------------------------- one version of crate image used here, as a dependency of crate gfx_texture
2 | extern crate rand;
3 | extern crate image;
| ------------------- one version of crate image used here, as a direct dependency of the current crate
= help: you can use cargo tree to explore your dependency tree
note: associated function defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston-gfx_texture-0.45.0\src\lib.rs:147:12
|
147 | pub fn from_image<F, C>(
| ^^^^^^^^^^
error[E0308]: mismatched types
--> src\main.rs:69:46
|
69 | texture.update(&mut texture_context, &buffer).unwrap();
| ------ ^^^^^^^ expected ImageBuffer<Rgba<u8>, Vec<u8>>, found a different ImageBuffer<Rgba<u8>, Vec<u8>>
| |
| arguments to this method are incorrect
|
note: two different versions of crate image are being used; two types coming from two different versions of the same crate are different types even if they look the same
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\image-0.24.9\src\buffer.rs:656:1
|
656 | pub struct ImageBuffer<P: Pixel, Container> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is the found type ImageBuffer
|
::: C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\image-0.25.6\src\buffer.rs:656:1
|
656 | pub struct ImageBuffer<P: Pixel, Container> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is the expected type image::buffer_::ImageBuffer
|
::: src\main.rs:1:1
|
1 | extern crate piston_window;
| --------------------------- one version of crate image used here, as a dependency of crate gfx_texture
2 | extern crate rand;
3 | extern crate image;
| ------------------- one version of crate image used here, as a direct dependency of the current crate
= help: you can use cargo tree to explore your dependency tree
note: method defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston-gfx_texture-0.45.0\src\lib.rs:181:12
|
181 | pub fn update<F, C>(
| ^^^^^^
For more information about this error, try rustc --explain E0308.
error: could not compile my_project (bin "my_project") due to 2 previous errors
let v = vec![10, 20, 30, 40, 50];
let first_three: Vec<_> = v.iter().take(3).cloned().collect();
println!("{:?}", first_three); // [10, 20, 30]
5. 使用 zip 兩個迭代器合併操作
let a = vec![1, 2, 3];
let b = vec![4, 5, 6];
let sum: Vec<_> = a.iter()
.zip(b.iter())
.map(|(x, y)| x + y)
.collect();
println!("{:?}", sum); // [5, 7, 9]
6. 使用 chain 串接多個迭代器
let a = vec![1, 2, 3];
let b = vec![4, 5, 6];
let chained: Vec<_> = a.iter()
.chain(b.iter())
.cloned()
.collect();
println!("{:?}", chained); // [1, 2, 3, 4, 5, 6]
7. 使用 skip 跳過前面幾個元素
let v = vec![10, 20, 30, 40, 50];
let skip_two: Vec<_> = v.iter().skip(2).cloned().collect();
println!("{:?}", skip_two); // [30, 40, 50]
以上就是多個 Rust Iterator 的常見函式組合用法,都是函數式風格替代傳統迴圈的好例子。
有需要我可以幫你示範更多複雜的串接或自訂閉包喔!
let v = vec![10, 15, 20, 25, 30];
let first_even = v.iter().find(|&&x| x % 2 == 0);
match first_even {
Some(n) => println!("找到的第一個偶數是 {}", n),
None => println!("沒有找到偶數"),
}
// 輸出: 找到的第一個偶數是 10
10. all 判斷所有元素是否符合條件
let v = vec![2, 4, 6, 8];
let all_even = v.iter().all(|&x| x % 2 == 0);
println!("全部都是偶數嗎?{}", all_even); // true
11. any 判斷是否有任一元素符合條件
let v = vec![1, 3, 5, 6];
let has_even = v.iter().any(|&x| x % 2 == 0);
println!("有偶數嗎?{}", has_even); // true
12. position 找出第一個符合條件元素的索引
let v = vec![3, 7, 10, 15];
let pos = v.iter().position(|&x| x > 8);
match pos {
Some(i) => println!("第一個大於8的元素索引是 {}", i),
None => println!("沒有找到大於8的元素"),
}
// 輸出: 第一個大於8的元素索引是 2
13. inspect 用於調試,對每個元素執行副作用
let v = vec![1, 2, 3];
let doubled: Vec<_> = v.iter()
.inspect(|x| println!("原始值:{}", x))
.map(|x| x * 2)
.collect();
println!("加倍後: {:?}", doubled);
// 輸出:
// 原始值:1
// 原始值:2
// 原始值:3
// 加倍後: [2, 4, 6]
14. collect 將迭代結果轉成其他集合容器(HashSet)
use std::collections::HashSet;
let v = vec![1, 2, 2, 3, 3, 3];
let set: HashSet<_> = v.into_iter().collect();
println!("{:?}", set); // {1, 2, 3} (順序不定)
15. flat_map 針對每個元素展開迭代器,再合併
let v = vec!["foo", "bar"];
let chars: Vec<_> = v.iter()
.flat_map(|s| s.chars())
.collect();
println!("{:?}", chars); // ['f', 'o', 'o', 'b', 'a', 'r']
16. chain 串接多個 iterator,不用多個變數
let v1 = vec![1, 2];
let v2 = vec![3, 4];
let v3 = vec![5, 6];
let combined: Vec<_> = v1.iter()
.chain(v2.iter())
.chain(v3.iter())
.cloned()
.collect();
println!("{:?}", combined); // [1, 2, 3, 4, 5, 6]
let v = vec![1, 3, 5, 7, 2, 4, 6];
let taken: Vec<_> = v.iter()
.take_while(|&&x| x < 5)
.cloned()
.collect();
println!("{:?}", taken); // [1, 3]
19. cycle 無限重複迭代器(通常配合 take)
let v = vec![10, 20, 30];
let repeated: Vec<_> = v.iter()
.cycle()
.take(7)
.cloned()
.collect();
println!("{:?}", repeated); // [10, 20, 30, 10, 20, 30, 10]
20. rev 配合 skip 跳過後逆序取值
let v = vec![1, 2, 3, 4, 5, 6];
let result: Vec<_> = v.iter()
.rev()
.skip(2)
.cloned()
.collect();
println!("{:?}", result); // [4, 3, 2, 1]
21. partition 根據條件拆分成兩個 collection
let v = vec![1, 2, 3, 4, 5, 6];
let (even, odd): (Vec<_>, Vec<_>) = v.into_iter()
.partition(|x| x % 2 == 0);
println!("偶數: {:?}", even); // [2, 4, 6]
println!("奇數: {:?}", odd); // [1, 3, 5]
22. collect 到 HashMap
use std::collections::HashMap;
let v = vec!["apple", "banana", "cherry"];
let map: HashMap<_, _> = v.iter()
.map(|&s| (s.len(), s))
.collect();
println!("{:?}", map);
// 可能輸出:{5: "apple", 6: "banana", 6: "cherry"} (HashMap 無序)
23. peekable 取得可先觀看下一元素的 iterator
let v = vec![10, 20, 30];
let mut iter = v.iter().peekable();
while let Some(val) = iter.next() {
println!("目前元素: {}", val);
if let Some(next_val) = iter.peek() {
println!("下一個元素: {}", next_val);
} else {
println!("沒有下一個元素");
}
}
// 輸出依序印出目前元素與下一個元素
24. chunks 以固定大小切割 slice
let v = vec![1, 2, 3, 4, 5, 6, 7];
for chunk in v.chunks(3) {
println!("{:?}", chunk);
}
// 輸出:
// [1, 2, 3]
// [4, 5, 6]
// [7]
25. windows 產生重疊長度固定的切片
let v = vec![1, 2, 3, 4, 5];
for window in v.windows(3) {
println!("{:?}", window);
}
// 輸出:
// [1, 2, 3]
// [2, 3, 4]
// [3, 4, 5]
let mut s = String::from("Hello World");
// 把 "World" 改成 "Rust"
s = s.replace("World", "Rust");
println!("{}", s); // Hello Rust
33. 「Zipping」N 個迭代器(須搭配 itertools crate)
use itertools::izip;
let a = vec![1, 2, 3];
let b = vec![4, 5, 6];
let c = vec![7, 8, 9];
for (x, y, z) in izip!(a.iter(), b.iter(), c.iter()) {
println!("{}, {}, {}", x, y, z);
}
// 會列印三列對應元素
34. sum 求所有元素總和
let v = vec![1, 2, 3, 4, 5];
let total: i32 = v.iter().sum();
println!("總和: {}", total); // 15
let text = "hello";
for trigram in text.as_bytes().windows(3) {
println!("{:?}", std::str::from_utf8(trigram).unwrap());
}
// 輸出:
// "hel"
// "ell"
// "llo"
3. 演算法設計
例如找最大連續子陣列,移動窗口檢查子狀態
排序演算法或比較演算法裡,也會用 windows 做細部比較
4. 模式匹配
在序列中尋找特定的固定模式
例如在 DNA 序列中搜尋特定基因序列
5. 數值計算
計算積分、差分時經常使用滑動視窗取出連續資料點
例如對資料取差分 (difference):
let data = vec![1, 3, 6, 10, 15];
for window in data.windows(2) {
println!("差分: {}", window[1] - window[0]);
}