Rust: イテレータメソッドの by_ref() と take_while() の組み合わせには気をつけようという話(てかドキュメントを読もう)
事の発端
take_while
というイテレータメソッドがある。
doc.rust-lang.org
詳しい説明は公式に任せるとして、 take_while
した後の残りが欲しかったが take_while
は self
を取るので 一回使ったら再利用できない。by_ref
を使ってrest
を取ろうとした。が、take_while
でイテレータが止まる条件を満たしたであろう最後に舐められた要素はdropされるという話でした。
例は下の playground で
まとめ
この記事書いてる時に
Because take_while() needs to look at the value in order to see if it should be included or not, consuming iterators will see that it is removed
の言及に気づいたのでドキュメントはちゃんと読みましょう
オチ
Rustで最高のIteratorといえば? => by_ref()
— 刃物休暇 (@Krout0n) 2021年6月22日
これ嘘ほんま許さん
— 刃物休暇 (@Krout0n) 2021年6月22日