Problem with raw pointers


#1

Hello!

code https://play.rust-lang.org/?gist=850814f58400a6a0880de725b1fca520&version=stable

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?


#2

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)); 

#3

https://play.rust-lang.org/?gist=bb7ee8922cf98e41272bdb7cd23a7b85&version=stable

will it be correct version? I also realized drop method for raw pointer


#4

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?


#5
  1. Thx, i understand that i have only one node, so it works
  2. Yes and Yes, i trying to write unsafe code, but i can’t write good version of binary tree too. If i try to walk tree, i have ownership problems and can’t compile. Also i saw version of tree with method insert of a Node

// 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


#6

I’d recommend reading http://cglab.ca/~abeinges/blah/too-many-lists/book/ - 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 :slight_smile:.


#7

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.


#8

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.