gpt4 book ai didi

rust - 修改选择器时,有没有办法在 Rust 中使用 match()?

转载 作者:行者123 更新时间:2023-11-29 08:04:25 25 4
gpt4 key购买 nike

这个问题的名字不好,但基本上,考虑这个简单的例子:

你有一个链表的形式:

struct Node<T> {
_next: Option<~Node<T>>,
_data: Option<T>
}

以及将元素添加到链中的“推送”操作:

/** Attach a node as the 'next' node in this chain */
fn push<'a>(&'a mut self, value: T) -> &'a mut ~Node<T> {
if (self._next.is_none()) {
self._push_node(~Node::new(value));
} else {
let tmp = self._next.take().unwrap();
let mut next = ~Node::new(value);
next._push_node(tmp);
self._push_node(next);
}
return self._next.as_mut().unwrap();
}

这行得通,但感觉它作为 match() 表达式而不是 if 语句会更整洁,例如:

/** Attach a node as the 'next' node in this chain */
fn push<'a>(&'a mut self, value: T) -> &'a mut ~Node<T> {
match self._next {
None => { self._push_node(~Node::new(value)); },
Some(ref v) => { <----------------------------- :(
let tmp = self._next.take().unwrap(); <------- ???
let mut next = ~Node::new(value);
next._push_node(tmp);
self._push_node(next);
}
}
return self._next.as_mut().unwrap();
}

但是,由于上面指示的行,这将不起作用;实际上我们正在修改 _next 的值,这是不可能发生的,因为我们借用了 self._next 作为匹配语句的 Some() 的范围。

有更好的方法吗?

你能否以某种方式将匹配语句声明为纯粹的匹配,这样一旦你进入 Some() => { ... } block 你就借用该值?

最佳答案

因为 Some(ref v) ,您正在借用该值。然后你没有使用它,所以 Some(_)会没事的。但实际上,您确实想要获取值(value)。所以你真正想要的是转移 take()比赛场外。

这是最终结果:

pub struct Node<T> {
next: Option<~Node<T>>,
data: Option<T>
}

/** Attach a node as the 'next' node in this chain */
pub fn push<'a>(&'a mut self, value: T) -> &'a mut ~Node<T> {
match self.next.take() {
None => self.push_node(~Node::new(value)),
Some(v) => {
let mut next = ~Node::new(value);
next.push_node(v);
self.push_node(next);
}
}
match self.next {
Some(ref mut t) => t,
None => unreachable!(),
}
// Sure, you could replace those four lines with self.next.as_mut().unwrap(),
// but I have a slight leaning towards highlighting the unreachable nature of
// the None branch. It makes it more explicit.
// Others will doubtless disagree with me on that point.
}

你也可以选择 Some(ref mut v)并操纵了&mut ~Node<T>直接赋值,但这可能需要改变 push_node 的方式作品。 (您没有显示它的代码,所以我只能猜测它的作用。)

我所做的其他一些文体更改:

  • 四个空格,而不是两个;
  • 不要用下划线作为前缀(Rust 有足够的隐私控制,不需要使用下划线);
  • if 两边没有括号表达式(好吧,现在它已被替换为 match ,所以没关系);
  • 如果匹配分支中只有一个语句,则不需要用花括号括起来——只需在它后面加一个逗号即可,
  • return x;可以写成 x当它在一个函数的末尾时。

关于rust - 修改选择器时,有没有办法在 Rust 中使用 match()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22340987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com