1 This error occurs because a borrow in a generator persists across a
4 Erroneous code example:
7 # #![feature(generators, generator_trait, pin)]
8 # use std::ops::Generator;
11 let a = &String::new(); // <-- This borrow...
12 yield (); // ...is still in scope here, when the yield occurs.
15 Pin::new(&mut b).resume();
18 At present, it is not permitted to have a yield that occurs while a
19 borrow is still in scope. To resolve this error, the borrow must
20 either be "contained" to a smaller scope that does not overlap the
21 yield or else eliminated in another way. So, for example, we might
22 resolve the previous example by removing the borrow and just storing
26 # #![feature(generators, generator_trait, pin)]
27 # use std::ops::Generator;
34 Pin::new(&mut b).resume();
37 This is a very simple case, of course. In more complex cases, we may
38 wish to have more than one reference to the value that was borrowed --
39 in those cases, something like the `Rc` or `Arc` types may be useful.
41 This error also frequently arises with iteration:
44 # #![feature(generators, generator_trait, pin)]
45 # use std::ops::Generator;
49 for &x in &v { // <-- borrow of `v` is still in scope...
50 yield x; // ...when this yield occurs.
53 Pin::new(&mut b).resume();
56 Such cases can sometimes be resolved by iterating "by value" (or using
57 `into_iter()`) to avoid borrowing:
60 # #![feature(generators, generator_trait, pin)]
61 # use std::ops::Generator;
65 for x in v { // <-- Take ownership of the values instead!
66 yield x; // <-- Now yield is OK.
69 Pin::new(&mut b).resume();
72 If taking ownership is not an option, using indices can work too:
75 # #![feature(generators, generator_trait, pin)]
76 # use std::ops::Generator;
80 let len = v.len(); // (*)
83 yield x; // <-- Now yield is OK.
86 Pin::new(&mut b).resume();
88 // (*) -- Unfortunately, these temporaries are currently required.
89 // See <https://github.com/rust-lang/rust/issues/43122>.