저는 녹에서 코드 데이 7 강림 대원을하고 있습니다. 그래서 같은 순서가 나무를 구문 분석 할 수 있습니다구조체를 두 위치에 저장하는 방법은 무엇입니까?
c
를 말한다
a(10)
c(5) -> a, b
b(20)
가 아이로 a
와 b
와 루트입니다.
나는 이것을 처리하기 위해 각 라인을 분석하고, 객체를 만들고, 이름으로 해시에 저장한다. 나중에 a
과 같이 자식으로 표시되면 해당 해시를 사용하여 개체를 찾아 아이로 적용 할 수 있습니다. b
과 같이 정의되기 전에 나타나는 경우 부분 버전을 만들고 해시를 통해 업데이트 할 수 있습니다. 위의 내용은 다음과 같습니다.
let mut np = NodeParser{
map: HashMap::new(),
root: None,
};
{
// This would be the result of parsing "a(10)".
{
let a = Node{
name: "a".to_string(),
weight: Some(10),
children: None
};
np.map.insert(a.name.clone(), a);
}
// This is the result of parsing "c(5) -> a, b".
// Note that it creates 'b' with incomplete data.
{
let b = Node{
name: "b".to_string(),
weight: None,
children: None
};
np.map.insert("b".to_string(), b);
let c = Node{
name: "c".to_string(),
weight: Some(5),
children: Some(vec![
*np.map.get("a").unwrap(),
// ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot move out of borrowed content
*np.map.get("b").unwrap()
// ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot move out of borrowed content
])
};
np.map.insert(c.name.clone(), c);
}
// Parsing "b(20)", it's already seen b, so it updates it.
// This also updates the entry in c.children. It avoids
// having to search all nodes for any with b as a child.
{
let mut b = np.map.get_mut("b").unwrap();
b.weight = Some(20);
}
}
노드를보고 해당 노드를 살펴볼 수 있습니다.
// And if I wanted to look at the children of c...
let node = np.map.get("c").unwrap();
for child in node.children.unwrap() {
// ^^^^ cannot move out of borrowed content
println!("{:?}", child);
}
녹이 싫어. NodeParser.map
과 Node.children
은 노드를 소유하고있는 것을 좋아하지 않습니다.
error[E0507]: cannot move out of borrowed content
--> /Users/schwern/tmp/test.rs:46:21
|
46 | *np.map.get("a").unwrap(),
| ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot move out of borrowed content
error[E0507]: cannot move out of borrowed content
--> /Users/schwern/tmp/test.rs:49:21
|
49 | *np.map.get("b").unwrap()
| ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot move out of borrowed content
그것은 for
루프가 이미 그것을 소유하는 NodeParser
에서 노드를 차용했기 때문에 반복 노드를 빌려하려고하는 것을 좋아하지 않는다.
error[E0507]: cannot move out of borrowed content
--> /Users/schwern/tmp/test.rs:68:18
|
68 | for child in node.children.unwrap() {
| ^^^^ cannot move out of borrowed content
제가 잘못하고있는 것을 이해한다고 생각하지만 올바른 방법을 모르겠습니다.
차용을 행복하게하기 위해 어떻게 구성해야합니까? NodeParser.map
과 Node.children
이 연결되어야하므로 복사가 옵션이 아닙니다.
Here is the code to test with. 실제 코드에서 Node
과 NodeParser
은 모두 구현과 메소드를 가지고 있습니다.
노드에 대한 참조를 직접 저장하는 대신 id (또는이 경우 name)로 저장하고 필요할 때 np.map에서 찾는다. – EvilTak
@EvilTak 제안에 감사드립니다. 그게 효과가있는 동안, 나는 그것보다는 주위에 차용 증서와 함께 작동 무언가를 찾고 있어요. – Schwern
더 쉬운 해결책 ('Rc's를 제외하고)이 존재할 때 왜 그렇게하고 싶은지 확실하지 않습니다. 왜 필요하지 않을 때 빌린 체커와 싸우는가? 차용 증표는 단순히 참조 수명을 초과하는 것을 방지하는 안전 메커니즘 일뿐입니다. 차용을 사용하는 경우에만 차용 증표로 작업하고 싶을 것입니다. – EvilTak