我嘗試遞回地通過一棵玫瑰樹。下面的代碼也能如愿以償,但我仍然有一個問題,由于借貸檢查器的問題,我需要克隆值。因此,如果有辦法從克隆改為更好的方式,那就更好了。
如果沒有 clone() rust 抱怨(正確地)我通過查看子節點和閉包中的第二次來借用自變數。
整個結構和代碼比下面顯示的更復雜、更大,但這是核心元素。我是否必須改變資料結構,或者我是否錯過了一些明顯的東西?如果資料結構是問題所在,你將如何改變它呢?
另外,NType 列舉在這里似乎有點用處,但我有一些額外的種類需要考慮。在這里,內部節點總是有孩子,而外部節點則沒有。
enum NType{
內在的。
外層
}
#[derive(Eq, PartialEq, Clone, Debug)]
struct Node {
//實際上并不是一個i32。在我的真實程式中,它是另一個結構體。
計數。i32。
n_type: NType。
兒童。Option<Vec<usize> >
}
#[derive(Eq, PartialEq, Clone, Debug)]
struct Tree {
節點。Vec<Node> 。
}
impl Tree{
pub fn calc(&mut self, features: &Vec<i32> ) -> i32{
//根是最后一個節點。
self.calc_h(self.nodes.len() - 1, features) 。
self.nodes[self.nodes.len() - 1].count.clone()
}
fn calc_h(&mut self, current: usize, features: &Vec<i32> ){
//做一些其他的事情來決定哪里要進入遞回,哪里不要。
//也可以使用這些功能。
if self.nodes[current].n_type == Inner{
//cloneing is very expensiv and destroys the performance。
self.nodes[current].children.as_ref().unwrap().clone()。 iter().for_each(|&n| self.calc_h(n, features) )。
self.do_smt(current)
}
self.do_smt(current)
}
}
編輯:
- Lagerbaer建議使用as_mut,但這導致當前是一個&mut usize,這并沒有真正解決問題。
- 將 childs 改為 children
uj5u.com熱心網友回復:
child的正確復數是children,所以這就是我在這個答案中提到的。據推測,這就是childs在你的代碼中的含義。
由于node.children已經是一個Option,最好的解決方案是.take()在迭代開始時將該向量從節點中取出,在結束時將其放入。這樣我們就可以避免在迭代程序中持有對tree.nodes的參考。
if self.nodes[current].n_type == Inner {
let children = self.nodes[current]。 children.take().unwrap()。
for &child in children.iter() {
self.calc_h(child, features)。
}
self.nodes[current].children = Some(children)。
}
注意,在回圈的情況下,行為與你的原始代碼不同,但如果樹的其他部分被正確實作,這不是你需要擔心的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/319298.html
標籤:
