隱私權政策

搜尋此網誌

技術提供:Blogger.

關於我自己

我的相片
目前從事軟體相關行業,喜歡閱讀、健身、喝調酒。習慣把遇到的問題記下來,每天做一些整理方便自己以後查。 Python、Rust、Kotlin等程式語言皆為自學,目前比較著重在Rust語言,歡迎一起討論。

2024年1月18日 星期四

Rust 迭代skip_while - 有條件的略過某些元素


迭代skip_while

skip_while跟skip[1]有一點點不一樣

skip是直接跳過前幾個元素

而skip_while則是可以設定條件

並根據條件跳過前幾個元素


文件這樣解釋

skip_while[2]

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
where
    Self: Sized,
    P: FnMut(&Self::Item) -> bool,

self是迭代器本身

輸入一個閉包

當達成閉包條件的時候會跳過這個元素

最後輸出一個迭代器

但要注意,如果有一個元素是false

則skip_while的工作就結束了

之後就不會跳過


舉個例子

假設我有一個數組

想要把前面小於3的元素都去除

可以這樣做

fn main() {
    let data = vec![1, 2, 3, 4, 5, 2, 7, 8, 9, 10];
    let res = data.into_iter().skip_while(|x| x < &3).collect::<Vec<_>>();
    println!("{:?}", res);
}
[3, 4, 5, 2, 7, 8, 9, 10]

先把data丟入迭代器中

使用skip_while,閉包條件設置小於3

這樣就可以把小於3的數字都去除

直到第一個出現大於等於3的

skip_while的工作就結束了

因此5後面還有一個2

他不會被去除


實際例子

假設我有一堆網址長這樣

    let link = vec![
        "1. https://www.google.com/",
        "2. https://www.facebook.com/",
        "3. https://www.youtube.com/?gl=TW&hl=zh-TW",
        "4. https://www.dcard.tw/",
        "5. https://shopee.tw/",
    ];

但我不想要編號本身

我希望從網址https開始

因此可以這樣做

fn main() {
    let link = vec![
        "1. https://www.google.com/",
        "2. https://www.facebook.com/",
        "3. https://www.youtube.com/?gl=TW&hl=zh-TW",
        "4. https://www.dcard.tw/",
        "5. https://shopee.tw/",
    ];

    let res: Vec<String> = link
        .into_iter()
        .map(|x| x.chars().skip_while(|c| !c.is_alphabetic()).collect())
        .collect::<Vec<_>>();
    println!("{:?}", res);
}
["https://www.google.com/",
"https://www.facebook.com/",
"https://www.youtube.com/?gl=TW&hl=zh-TW",
"https://www.dcard.tw/", "https://shopee.tw/"]

先將網址數組丟入迭代器中

map[3]取出每個網址

並且判斷每個網址的字元char

再使用skip_while並以is_alphabetic[4]判斷是否為字母

當為字母實則結束skip

最後輸出


參考資料

[1] https://lageeblog.blogspot.com/2024/01/rust-skip.html

[2] https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.skip_while

[3] https://lageeblog.blogspot.com/2023/10/rust-map.html

[4] https://lageeblog.blogspot.com/2024/01/rust-isalphabeticisalphanumeric.html

0 comments:

張貼留言