]> git.proxmox.com Git - rustc.git/blob - src/doc/edition-guide/src/rust-2021/IntoIterator-for-arrays.md
New upstream version 1.54.0+dfsg1
[rustc.git] / src / doc / edition-guide / src / rust-2021 / IntoIterator-for-arrays.md
1 # IntoIterator for arrays
2
3 ## Summary
4
5 ## Details
6
7 Until Rust 1.53, only *references* to arrays implement `IntoIterator`.
8 This means you can iterate over `&[1, 2, 3]` and `&mut [1, 2, 3]`,
9 but not over `[1, 2, 3]` directly.
10
11 ```rust,ignore
12 for &e in &[1, 2, 3] {} // Ok :)
13
14 for e in [1, 2, 3] {} // Error :(
15 ```
16
17 This has been [a long-standing issue][25], but the solution is not as simple as it seems.
18 Just [adding the trait implementation][20] would break existing code.
19 `array.into_iter()` already compiles today because that implicitly calls
20 `(&array).into_iter()` due to [how method call syntax works][22].
21 Adding the trait implementation would change the meaning.
22
23 Usually we categorize this type of breakage
24 (adding a trait implementation) 'minor' and acceptable.
25 But in this case there is too much code that would be broken by it.
26
27 It has been suggested many times to "only implement `IntoIterator` for arrays in Rust 2021".
28 However, this is simply not possible.
29 You can't have a trait implementation exist in one edition and not in another,
30 since editions can be mixed.
31
32 Instead, we decided to add the trait implementation in *all* editions (starting in Rust 1.53.0),
33 but add a small hack to avoid breakage until Rust 2021.
34 In Rust 2015 and 2018 code, the compiler will still resolve `array.into_iter()`
35 to `(&array).into_iter()` like before, as if the trait implementation does not exist.
36 This *only* applies to the `.into_iter()` method call syntax.
37 It does not affect any other syntax such as `for e in [1, 2, 3]`, `iter.zip([1, 2, 3])` or
38 `IntoIterator::into_iter([1, 2, 3])`.
39 Those will start to work in *all* editions.
40
41 While it's a shame that this required a small hack to avoid breakage,
42 we're very happy with how this solution keeps the difference between
43 the editions to an absolute minimum.
44 Since the hack is only present in the older editions,
45 there is no added complexity in the new edition.
46
47 [25]: https://github.com/rust-lang/rust/issues/25725
48 [20]: https://github.com/rust-lang/rust/pull/65819
49 [22]: https://doc.rust-lang.org/book/ch05-03-method-syntax.html#wheres-the---operator