Option does not implement copy trait

I am a beginner and rust and I can't fix the issue no matter what I try.

This is the error:

use of moved value: `current_node`
value used here after moverustc(E0382)

closest_value_bst.rs(24, 28): value moved here

closest_value_bst.rs(15, 9): move occurs because `current_node` has type `std::option::Option<std::boxed::Box<basic::closest_value_bst::BST>>`,
 which does not implement the `Copy` trait 

I tried references as well but I end up having even more errors..

What would be a standard way of solving these issues?

current_node.as_ref().unwrap() or current_node.as_mut().unwrap()

Same thing

Could you give us some code in play.rust-lang.org/ to play around ?

Yes.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3bd1103192818f65aa09e6a091b84d8c

This is my first week of rust pretty much.. Try not to judge the code too much :joy:

Why no use Option::take and while let
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6cc4e53f668c50055bf7c0fd6432243d
This works

3 Likes

No need for take in this particular example: since current_node is not used again before reassigning it, you can just move out of it.

pub fn algo<'a>(tree: Option<Box<BST>>, target: i32, mut closest: i32) -> i32 {
    let mut current_node = tree;

    while let Some(node) = current_node {
        if (target - closest).abs() > (target - node.value).abs() {
            closest = node.value;
        }

        if target < node.value {
            current_node = node.left;
        } else if target > node.value {
            current_node = node.right;
        } else {
            break;
        }
    }
    closest
}
2 Likes

Can't believe that was only mistake to the algorithm... Thank you everyone :heart:

Actually it is an ownership problem.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.