Hi, new rustacean here..
I realize how stupid the title topic sounds believe me, I can't explain this to my self either.
So I'm coming from a high level language and I'm probably missing something specific for low level languages, but since I couldn't find someone else experiencing the same issue nor any logic explanation in either my head or documentation, that's why I decided to ask the experienced.
I'm having impl A
and impl B
both with methods inside. impl A
is calling a method from impl B
which is created to iterate over a custom value which is HashMap<String, Value>
while Value is a struct of that can hold some other data. In that specific case it holds more HashMap<String, Value>
. My iterative method tries to encounter existing keys deep nested into the whole thing which are differently named on each level. The method that's being called to iterate from impl B
is recursive for that reason. The recursive method returns Option<&'c Value>
, lifetime is chained with the lifetime of the origin hashmap provided at first. So my body looks something like that:
pub fn hash_iterate<'c>(needle: &str, hash: &'c HashMap<String, Value>) -> Option<&'c Value>
The calling impl looks something like that:
impl A {
fn analyze() {
B::hash_iterate("needle", hashmap);
}
}
impl B {
pub fn hash_iterate<'c>(needle: &str, hash: &'c HashMap<String, Value>) -> Option<&'c Value>
return match hash.get(needle.to_string()) {
Some(v) => {
// I have some complex if condition here that enters recursion
if complex_condition_true {
hash_iterate("new_needle_here", &v.clone().unwrap());
}
hash.get(needle.to_string())
}
None => None
}
}
}
So you can imagine that I'm providing a route which the recursion should go through. However if any of the paths are not found we'd like to return None. If all recursive calls are successful we'd like to return the last value we've encountered.
The paths are like path1.path2.path3 (we iterate over 2 hashmaps in the recursion that way because we'd like to check if path3 exists at all)
What happens with the recursive method is what amazes me. It returns strange results like the following:
- We search for the whole route and path1 doesn't exist on first hit, it returns None successfully
- We search for the whole route and path1 exists, so we enter it and search for path2 that doesn't exists the method returns Some(path1) instead of None
- We search for the whole route and path1 exists, path2 exists, path3 doesn't exists, the method returns Some(path2).
Interesting facts:
When returning, the method goes through None arm match and still returns Some.
Edit: Fixed the code formatting, sorry about that.