以下代码未通过借位检查器,因为Label-A使用Label-B消耗的值,但该代码实际上是安全的:Label-A由processed
保护,仅在运行Label-B时才设置。
我如何才能告诉编译器依赖关系,或者如果不能,则该解决这个问题的成语是什么?
(使X
Copy
/Clone
Not Acceptable ,也不使consume
成为引用,Rc<X>
都没有吸引力(数据结构已经相当复杂))
struct X(i32);
fn consume1(_x: X) {
()
}
fn consume2(_x: X) {
()
}
fn predicate(_x: &X) -> bool {
true
}
pub fn main() {
let xs = vec![X(1), X(2)];
for x in xs {
let mut processed = false;
// for _ in _ {
if predicate(&x) {
consume1(x); // Label-B
processed = true;
}
// } end for
// this for loop here is just to show that the real code
// is more complicated, the consume1() is actually called
// (somehow) inside this inner loop
// some more code
if !processed {
consume2(x); // Label-A
}
}
}
最佳答案
除非我误解了,否则我认为对您来说最好的选择是使用“选项”。这样,您还可以摆脱该boolean
标志。
struct X( i32 );
fn consume1( _x: X ) { }
fn consume2( _x: X ) { }
fn predicate( _x: &X ) -> bool {
true
}
pub fn main( ) {
let xs = vec![ Some( X( 1 ) ), Some( X( 2 ) ) ];
for mut x in xs {
if predicate( x.as_ref( ).unwrap( ) ) {
consume1( x.take( ).unwrap( ) );
}
if let Some( x ) = x {
consume2( x );
}
}
}
关于rust - Rust:如何告诉借位检查员此举取决于 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66298424/