Array – use ‘iterator’ instead of ‘VEC’ as much as possible?

Is it considered a good style to accept iterator T when a function takes a series of values as parameters Not VEC t

In this way, the caller can decide how to store the series (in VEC, [t; n] or anything else, which should actually be optional < T >) In addition, you don't need to convert anything you have into VEC, and after applying some iterator modifiers, you don't need to collect(). So it should be faster!

What did I miss, or did I do it?

Solution

The function you describe should usually be an intoiterator < item = t >; Therefore, it can accept iterators < T > and VEC t as inputs

This can also be used in combination with other technologies; For example, the method concat will accept & str (forced by auto deref / ref) & [string] (and & VEC < string) & [& STR] (and & VEC &, & STR iterator, string iterator, etc.:

use std::borrow::Borrow;

fn concat<T: Borrow<str>,Iter: IntoIterator<Item = T>>(iter: Iter) -> String {
    iter.into_iter()  // -> impl Iterator<Item = T>
        .map(|s| s.borrow()) // -> impl Iterator<Item = &str>
        .collect()  // -> String
}

(in fact, this specific example is usually more suitable for sliceconcatext because it can calculate how long the final result will be, so it can allocate the correct length string at one time, but this is only a proof of concept and how many fancy techniques can be combined.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>