Summary

Add a once function to std::iter to construct

作る、構成体
an iterator yielding
産出する、出力する
a given
与えられた
value one time, and an empty function to construct
作る、構成体
an iterator yielding
産出する、出力する
no values.

Motivation

This is a common task when working with iterators. Currently, this can be done in many ways, most of which are unergonomic, do not work for all types (e.g. requiring Copy/Clone), or both. once and empty are simple to implement,

実装する
simple to use, and simple to understand.

Detailed design
設計(する)

once will return a new struct,

構造、構造体
std::iter::Once<T>, implementing
実装する
Iterator. Internally, Once<T> is simply a newtype wrapper around std::option::IntoIter<T>. The actual
実際の
body of once is thus
それゆえに、従って、
trivial:

#![allow(unused)] fn main() { pub struct Once<T>(std::option::IntoIter<T>); pub fn once<T>(x: T) -> Once<T> { Once( Some(x).into_iter() ) } }

empty is similar:

似ている、同様の

#![allow(unused)] fn main() { pub struct Empty<T>(std::option::IntoIter<T>); pub fn empty<T>(x: T) -> Empty<T> { Empty( None.into_iter() ) } }

These wrapper structs

構造、構造体
exist to allow
許可する、可能にする
future backwards-compatible changes, and hide the implementation.
実装

Drawbacks

Although a tiny amount of code, it still does come with a testing, maintainance, etc. cost.

It's already possible to do this via Some(x).into_iter(), std::iter::repeat(x).take(1) (for x: Clone), vec![x].into_iter(), various

さまざまな
contraptions involving iterate...

The existence of the Once struct

構造、構造体
is not technically necessary.

Alternatives
代わりのもの、選択肢

There are already many, many alternatives

代わりのもの、選択肢
to this- Option::into_iter(), iterate...

The Once struct

構造、構造体
could be not used, with std::option::IntoIter used instead.

Unresolved questions

Naturally, once is fairly bikesheddable. one_time? repeat_once?

Are versions of once that return &T/&mut T desirable?