Rust 有没有更好的方法来获取不相交结构字段的可变引用?
我有一些生锈的代码,我发现很臭。我想同时从结构的字段中获取可变引用,但Rust当然不允许同时有多个可变引用 我目前所做的基本上是创建一个新类型的元组,然后将两种不同类型的模式匹配成单独的Rust 有没有更好的方法来获取不相交结构字段的可变引用?,rust,Rust,我有一些生锈的代码,我发现很臭。我想同时从结构的字段中获取可变引用,但Rust当然不允许同时有多个可变引用 我目前所做的基本上是创建一个新类型的元组,然后将两种不同类型的模式匹配成单独的ref mut模式。在实践中,我并不怎么喜欢这种方式 struct Foo; impl Foo { fn foo(&mut self, bar: &mut Bar) { bar.bar(); } } struct Bar; impl Bar { fn
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();
}
我有没有更好的办法?或者是关于构造代码的一般方法的一些想法,这样我就不需要这个新类型了?您不需要重新键入元组,您可以直接创建元组结构:
struct FooBar(Foo, Bar);
然后,您可以非常简洁地编写代码,如下所示
fn foobar(&mut self) {
self.0.foo(&mut self.1);
println!("foobar");
}
通过使用元组索引而不是let绑定。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();
}
这将编译并运行