Fluent Rust - taking values from &mut

Migo·2023년 8월 21일
0

Fluent Rust

목록 보기
2/27
post-thumbnail

Suppose your struct consists of the following field:

pub struct Transaction{
    items: Vec<String>,
    amount: i32,
    state: String
}

And you expose public interface to change the state of Transaction:

impl Transaction {
    pub fn change_string(&mut self){
        self.state  = self.state.change_string()

    }
}

In this case, if the method change_string() on state takes ownership, it won’t be working, erroring out:

Cannot move out of self.state which is behind a mutable reference move occurs because self.state has type String, which does not implement the Copy trait

The reason for that is quite simple. the change_string method(your public interface) takes &mut so according to the ownership tree rule, you can’t move the ownership of value but only change.

But the method change_string you delegate to its field tries to take the ownership, thereby Rust compiler rejecting such an attempt.

Solution

Solution to this problem is quite simple yet requires understanding over idiomatic Rust.

1. change the changeable value to Option<type>

pub struct Transaction{
    items: Vec<String>,
    amount: i32,
    state: Option<String>
}

2. use .take() on Option<type>

impl Transaction {
    pub fn change_string(&mut self){
        if let Some(s)  = self.state.take(){
            self.state = Some(s.change_string())
        }
    }
}

So, what .take() does is it takes the value of Option and leaves it None. As that counts as changing value, as opposed to taking ownership, the Rust compiler doesn’t complain.

profile
Dude with existential crisis

0개의 댓글

관련 채용 정보