有没有更好的方法来获取不相交结构体字段的可变引用?

3

我有一些Rust代码,感觉写得不够好。我想同时从结构体的字段中获取可变引用,但是Rust不允许同时存在多个可变引用。

目前我所做的就是基本上创建一个元组的新类型,然后将两种不同类型分开到单独的ref mut模式匹配中。实际上并不是很喜欢这种方式的外观。

struct Foo;

impl Foo {
    fn foo(&mut self, bar: &mut Bar) {
        bar.bar();
    }
}

struct Bar;

impl Bar {
    fn bar(&mut self) {
        println!("bar")
    }
}

struct FooBar((Foo, Bar));

impl FooBar {
    fn foobar(&mut self) {
        let &mut FooBar((ref mut foo, ref mut bar)) = self;
        foo.foo(bar);
        println!("foobar");
    }
}

fn main() {
    let mut foobar = FooBar((Foo, Bar));
    foobar.foobar();
}
Rust Playground 有没有更好的方法来完成这个任务?或者关于如何构建代码结构的一般性思路,以便我不需要这个newtype?
2个回答

4
您不需要为元组定义新类型,可以直接创建一个元组结构体:
struct FooBar(Foo, Bar);

那么你可以编写非常简洁的代码,例如

fn foobar(&mut self) {
    self.0.foo(&mut self.1);
    println!("foobar");
}

通过使用元组索引而不是let绑定。

3

Rust的借用分析原生支持借用不相交的字段。

你可以使用类似元组的struct或常规的struct,它们都可以正常工作:

struct Foo;

impl Foo {
    fn foo(&mut self, bar: &mut Bar) {
        bar.bar();
    }
}

struct Bar;

impl Bar {
    fn bar(&mut self) {
        println!("bar")
    }
}

struct Tupled(Foo, Bar);

impl Tupled {
    fn foobar(&mut self) {
        self.0.foo(&mut self.1);
    }
}

struct Named {
    foo: Foo,
    bar: Bar,
}

impl Named {
    fn foobar(&mut self) {
        self.foo.foo(&mut self.bar);
    }
}

fn main() {
    let mut tupled = Tupled(Foo, Bar);
    tupled.foobar();

    let mut named = Named{ foo: Foo, bar: Bar };
    named.foobar();
}

这段代码可以在Rust Playground上编译并运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接