代码在没有借用的情况下工作,但我无法借用它

问题描述 投票:1回答:1

我有一些代码并且它可以工作,但AFAIK借用是专门为避免像split_text方法那样手动传入和传出方法。

fn main() {
    println!("Hello, world!");
    let mut test = String::from("12345");
    let mut obj1 = Object {
        text: test.as_mut_str(),
        next: None,
    };
    for i in 0..5 {
        obj1 = obj1.split_text(4 - i);
        if let Some(obj) = obj1.next.as_ref() {
            println!("{}", obj.text);
        }
    }
}

struct Object<'a> {
    text: &'a mut str,
    next: Option<Box<Object<'a>>>,
}

impl<'a> Object<'a> {
    fn split_text(mut self, count: usize) -> Self {
        let tmp = self.text;
        let (part1, part2) = tmp.split_at_mut(count);
        self.text = part1;
        let obj2 = Object {
            text: part2,
            next: None,
        };
        self.next = Some(Box::new(obj2));
        self
    }
}

(Qazxswpoi)

但我无法弄清楚如何通过借阅检查

Playground

导致错误

impl<'a> Object<'a> {
    fn split_text(&'a mut self, count: usize) {
        let tmp = &mut self.text;
        let (part1, part2) = tmp.split_at_mut(count);
        self.text = part1;
        let obj2 = Object {
            text: part2,
            next: None,
        };
        self.next = Some(Box::new(obj2));
    }
}

(Qazxswpoi)

有没有办法使这个代码工作?

rust
1个回答
1
投票

问题是你在error[E0499]: cannot borrow `obj1` as mutable more than once at a time --> src/main.rs:11:9 | 11 | obj1.split_text(4 - i); | ^^^^ mutable borrow starts here in previous iteration of loop error[E0502]: cannot borrow `obj1.next` as immutable because it is also borrowed as mutable --> src/main.rs:12:28 | 11 | obj1.split_text(4 - i); | ---- mutable borrow occurs here 12 | if let Some(obj) = obj1.next.as_ref() { | ^^^^^^^^^ | | | immutable borrow occurs here | mutable borrow later used here error[E0506]: cannot assign to `self.text` because it is borrowed --> src/main.rs:27:9 | 23 | impl <'a> Object<'a> { | -- lifetime `'a` defined here 24 | fn split_text(&'a mut self, count:usize) { 25 | let tmp = &mut self.text; | -------------- borrow of `self.text` occurs here 26 | let (part1, part2) = tmp.split_at_mut(count); | ----------------------- argument requires that `self.text` is borrowed for `'a` 27 | self.text = part1; | ^^^^^^^^^^^^^^^^^ assignment to borrowed `self.text` occurs here 函数中借用Playground可变对象obj1生命周期,直到split_text函数的末尾。

'a

你想为main函数可变地借用它,即不同的(较小的)生命周期 - 你可以忽略或指定另一个 - 比如说fn main() { println!("Hello, world!"); let mut test = String::from("12345"); let mut obj1 = Object { // 'a start text: test.as_mut_str(), next: None, }; for i in 0..5 { obj1 = obj1.split_text(4 - i); // borrow for 'a lifetime, // Won't work in next iteration if let Some(obj) = obj1.next.as_ref() { // Won't work println!("{}", obj.text); } } } // 'a end

split_text

明确的不同生命期版本(仅为完整性):

'b

此外,只有在需要时才能制作可变的东西。我改变了可变切片并分裂成正常。

© www.soinside.com 2019 - 2024. All rights reserved.