N
N
Nast22019-08-01 13:59:14
Rust
Nast2, 2019-08-01 13:59:14

When calling a method of a child structure from a parent, I get an error, cannot move out of borrowed content, how can I fix it?

Code example:
https://play.rust-lang.org/?version=stable&mode=de...

struct Child {
    v: Option<i32>,
}

impl Child {
    fn get_value(&self) -> Result<i32, &str> {
        match self.v {
            Some(v) => Ok(v),
            None => Err("Values is undefined")
        }
    }
}

struct Parent {
    child: Option<Child>,
}

impl Parent {
    fn get_child_value(&self) -> Result<i32, &str> {
        return match self.child {
            Some(child) => child.get_value(),
            None => Err("Child is undefined")
        }
    }
}

fn main() {
    let ch = Child{v: Some(2)};
    let parent = Parent{child: Some(ch)};
    parent.get_child_value();
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Lesnikov, 2019-08-01
@Nast2

The easiest way, kmk, would be to replace `Some(child)` with `Some( ref child)`, so that instead of moving the child, it would be borrowed.
Or you can pass a link to the match itself: `return match & self.child {`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question