Hello,
I'm relatively new to Rust and I have a question about raw pointers and their "safe" use.
From what I understand pointers can be a great tool to simplify (and speed up) the code in certain circumstances, but I fail to understand how can they fit "safely" (or unsafely) in the language.
One of the use cases I saw is stuff like Trees and parent pointers, where you have something like this:
struct Node {
left: Box<Node>,
right: Box<Node>,
parent: *mut Node
}
Now, reading the Rustonomicon I see that pointers can essentially be assumed not aliasing with anything that is not a pointer itself (variables, references), so my question is, when you have something like the above, where you have 2 things pointing to the same memory (nominally a pointer and Box), how is it possible to use it at all?
I read around (blogs/articles) that if you are using something like the above you need to be sure you never hold two references (one at least mutable) at the same time and you are fine, but this seems impossible to prove in many cases.
Like, if I write a function that takes a Node and accesses the pointer (and only the pointer) , in the context of that function yeah, there are no other references accessing parent, but in the context that calls the function there could be references alive across the function calls. Vetting your entire call graph in order to make sure that across a function call you never hold a pointer to an object seems very very difficult and not maintainable
So it seems to me that the pattern above is not usable in practice and the only safe way (if you want to go pointers) is to actually go full blown pointers like
struct Node {
left: *mut Node,
right: *mut Node,
parent: *mut Node
}
And allocate the memory either manually or using box and consuming it into a pointer.
Does what I just said make sense or am I missing something? Is all the code I mentioned above using both Box and pointers most of the time invalid?
Is there a resource on how to use pointers in a way that doesn't potentially cause UB in your code?
Thanks