Method borrowing a struct's field (and not the struct as a whole)

Thanks to splitting borrows, we can borrow two different fields of a same struct without any issue, as such:

struct Foo {
    a: Vec<Bar>,
    b: i32
}

struct Bar {
    a: Vec<i32>
}

fn main() {
    let mut foo = Foo {a: vec![Bar {a: vec![2]}], b: 0};
    let bar = &foo.a[0];
    foo.b = bar.a[0];
}

Here, foo.a and foo.b are borrowed at the same time without issue. However, if we were to wrap everything in methods...

impl Foo {
    pub fn get(&self, i: usize) -> &Bar {
        &self.a[i]
    }
    pub fn set_b(&mut self, val: i32) {
        self.b = val;
    }
}

fn main() {
    let mut foo = Foo {a: vec![Bar {a: vec![2]}], b: 0};
    let bar = foo.get(0);
    foo.set_b(bar.a[0]);
}

...it simply doesn't compile. And I understand why ! My question is, is there any way to hint the compiler that get only borrows self.a and set_b only borrows b ?

In my actual code, I do various different operations in my methods, and directly accessing the fields is just not a good idea

Here is a playground that I used to check what I was saying on this simple Foo/Bar example

1 Like

There isn't, put perhaps there will be in the future, some day.

3 Likes

Ok, thanks !

Rust Team members have expressed an interest in having something like this built into the language some day, but it's not there yet.

In the meanwhile, you can use view structs or consider some of the other work-arounds in that article.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.