【问题标题】:Change mutable reference in a loop in Rust在 Rust 的循环中更改可变引用
【发布时间】:2021-08-11 21:24:47
【问题描述】:

我有一个像这样的简单递归数据结构:

    struct X{
       i:u32,
       n:Option<Box<X>>
    }
    fn new(i:u32,x:X)->X{
       X{i,n:Some(Box::new(x))}
    }

现在我想循环迭代它。

    let mut x = new(7,new(3,new(4,new(0,X{i:3,n:None}))));
    let mut i:&mut X = &mut x;
    while let Some(n) = &mut i.n{
        println!("{}",i.i);
        i = &mut n;
    }

不幸的是,借用检查器似乎对这段代码不满意。有什么办法让它工作,还是我应该使用原始指针?

【问题讨论】:

    标签: loops recursion rust borrow-checker


    【解决方案1】:

    没关系。我想到了。事实证明它并不复杂

        use std::borrow::BorrowMut;
    
        struct X{
            i:u32,
            n:Option<Box<X>>
        }
        fn n(i:u32,x:X)->X{
            X{i,n:Some(Box::new(x))}
        }
        let mut x = n(7,n(3,n(4,n(0,X{i:3,n:None}))));
        let mut i:&mut X = &mut x;
        while let Some(n) = &mut i.n{
            println!("{}",i.i);
            i = n.borrow_mut();
        }
    

    【讨论】:

      猜你喜欢
      • 2011-02-19
      • 1970-01-01
      • 2013-06-03
      • 2016-03-10
      • 1970-01-01
      • 2022-11-23
      • 2023-04-05
      • 1970-01-01
      • 2015-07-17
      相关资源
      最近更新 更多