What are rust borrowing rules for volatile internal links?

It is not intuitive for me why a program like

#[derive(Debug)]
struct Test {
    buf: [u8; 16],
}

impl Test {
    fn new() -> Test {
        Test {
            buf: [0u8; 16],
        }       
    }   

    fn hi(&mut self) {
        self.buf[0] = 'H' as u8; 
        self.buf[1] = 'i' as u8; 
        self.buf[2] = '!' as u8; 
        self.print();
    }   

    fn print(&self) {
        println!("{:?}", self);
    }   
}

fn main() {
    Test::new().hi();
}

compiles and runs without any problems, but a program like

#[derive(Debug)]
enum State {
    Testing([u8; 16]),
}

#[derive(Debug)]
struct Test {
    state: State,
}       

impl Test {
    fn new() -> Test {
        Test {
            state: State::Testing([0u8; 16]),
        }
    }   

    fn hi(&mut self) {
        match self.state {
            State::Testing(ref mut buf) => {
                buf[0] = 'H' as u8;
                buf[1] = 'i' as u8;
                buf[2] = '!' as u8;
                self.print();
            },
        }
    }

    fn print(&self) {
        println!("{:?}", self);
    }
}

fn main() {
    Test::new().hi();
}

when compiling with an error

error [E0502]: cannot be taken *selfas immutable, because it is self.state.0also borrowed as mutable

Since both programs perform essentially the same thing, the second does not seem to be somehow more dangerous in terms of memory. I know that there must be something about the rules for borrowing and defining the scope that I have to miss, but I have no idea what.

+4
source share
2 answers

match self.state. , match. self.print(), self. , self . self.print() match, .

, , Rust, : # 6393, # 811.

+1

hi, print , match:

fn hi(&mut self) {
    match self.state {
        State::Testing(ref mut buf) => {
            buf[0] = 'H' as u8;
            buf[1] = 'i' as u8;
            buf[2] = '!' as u8;
        },
    }
    self.print();
}

- match . , tuple enum ( ), , , .

+3

Source: https://habr.com/ru/post/1666761/


All Articles