Hello!
code Rust Playground
when i using such way
self.base_node = &mut Node::new(value);
it look like garbage in a base_node, but if i use temporary variable x (lines 36-37)
it works fine. What is the difference?
Hello!
code Rust Playground
when i using such way
self.base_node = &mut Node::new(value);
it look like garbage in a base_node, but if i use temporary variable x (lines 36-37)
it works fine. What is the difference?
In the garbage case you're taking a reference to a temp that's dropped immediately (the raw pointer doesn't keep it alive). In the temporary variable case, the x
is kept alive until the end of scope. You can try the following to see the same thing manifest itself:
{
let mut x = Node::new(value);
self.base_node = &mut x;
} // 'x' lifetime ends, it's dropped - the raw pointer is dangling now
println!("value={:?}, node={:?}", &value, (*self.base_node));
will it be correct version? I also realized drop method for raw pointer
Yeah, that will prevent the memory from being dropped (freed). Your Drop
will need to handle traversing the nodes though - what you have there just frees the base_node
but not the child trees.
Are you specifically learning how to write unsafe Rust code? Or would you rather write a binary tree in safe rust but didn't know how to structure it?
// something like this
fn insert(&mut self, value: T) {
if self.left.is_some() {
self.left.insert(value)
}
}
but i think i will have stackoverflow
I'd recommend reading Learning Rust With Entirely Too Many Linked Lists - it's about linked lists, but trees would be dealt with similarly. Just note though that these types of data structures are hard to write in safe Rust so make sure you're comfortable with the language basics before diving into that .
i'm starting learning languages from implementing basic structs and other primitives, but i didn't thought that it will be problem in rust. Thanks for reply, i will try to write another things.
Yeah, you're not alone - I think a lot of people try to implement these types of data structures because that's a common exercise in other languages. However, in Rust you're immediately thrown in with the sharks (borrowing, ownership, iterators, generics, mutability, etc) - it ends up being a very frustrating experience for some. So, to avoid that, I would suggest going lighter with other exercises to get familiar with the language.