ライフタイムとライフタイム付き可変参照
struct MutableDataWithLifeTime<'a> { // ライフタイム付き可変参照 val: &'a mut i32, } struct ShortLifeTime; impl ShortLifeTime { fn take_data<'a>(data: &'a mut MutableDataWithLifeTime<'a>) { *data.val *= 2; } } struct LongLifeTime; impl LongLifeTime { fn take_data<'a>(data: MutableDataWithLifeTime<'a>) { // 長いライフタイム let mut data = data; loop { // 短いライフタイム // error[E0499]: cannot borrow `data` as mutable more than once at a time ShortLifeTime::take_data(&mut data); } } } /* error[E0499]: cannot borrow `data` as mutable more than once at a time | 21 | ShortLifeTime::take_data(&mut data); | ^^^^^^^^^ `data` was mutably borrowed here in the previous iteration of the loop error: aborting due to previous error For more information about this error, try `rustc --explain E0499`. */
- 長いライフタイムを持つブロックでループを回す
- ループ内で可変参照を渡す → NG
理由は、借用ルールの「複数の可変参照を同時に借用出来ない」ため。