Hey all!
I'm currently working on an swc plugin which replaces parts of a JavaScript DOM.
I came to realize that working with swcs complex data structures involving nested Boxes and enums which must be matched against is quite cumbersome when it comes to borrow checking.
This is an excert of my method which parses a node and, in case it's not a nameof expression, returns None and otherwise returns an Err (possibly holding immutable parts of the node) or an Ok (holding mutable parts of the node):
Sadly, I can't find myself able to find a way to work around the error reported in this code snippet.
Could you help me understand what I'm doing wrong or how I can improve this piece of code?
I didn't try to identify the underlying cause or to come up with a clever solution. I often find that error types with lifetimes are a cause of borrowing problems because they're propagated upwards, and since they are infrequently created (often but not always), I sometimes resort to cloning their contents so I can remove the lifetime annotation. That worked in this case. playground
Oooh amazing, thank you so much for your rapid answer!
So, with this being a clone of a mere reference, this doesn't raise the memory consumption considerably, right?
If you don't want to change to non-borrowing error types, the OP error is due to a conditional return of a borrow situation, which Polonius should eventually accept. This crate may provide a stop-gap (I didn't try it).
Cloning the String (in the Atom) does allocate a new String. That's why I mentioned that I normally only use this approach when the error is infrequently created; if infrequent, allocations don't matter nearly as much.
Thank you so much - this actually was a really good read and helped me get my head halfway wrapped around what this error is and why it happens. So... If I understand correctly, references created in if let and match calls and then featured in returns live to the end of the function for all code paths.
I addressed this issue by using the same call object for all returns in the function: