How to write a Rust function that takes an iterator?

后端 未结 3 2034
遇见更好的自我
遇见更好的自我 2020-11-27 20:57

I\'d like to write a function that accepts an iterator and returns the results of some operations on it. Specifically, I\'m trying to iterate over the values of a Has

3条回答
  •  甜味超标
    2020-11-27 21:22

    This behaviour is a little unintuitive from those with a Python background rather than, say, a C++ background, so let me clarify a little.

    In Rust, values are conceptually stored inside the name that binds them. Thus, if you write

    let mut x = Foo { t: 10 };
    let mut y = x;
    x.t = 999;
    

    y.t will still be 10.

    So when you write

    let x: Iterator;
    

    (or the same in the function parameter list), Rust needs to allocate enough space for any value of type Iterator. Even if this was possible, it wouldn't be efficient.

    So what Rust does instead is offer you the option to

    • Put the value on the heap, eg. with Box, which gives Python-style semantics. Then you can take generically with &mut Iterator.

    • Specialize each function invocation for each possible type to satisfy the bound. This is more flexible, since a trait reference is a possible specialization, and gives the compiler more opportunities for specialization, but means you can't have dynamic dispatch (where the type can vary dependent on runtime parameters).

提交回复
热议问题