Skip to content

Commit

Permalink
fix: separate compiler error from code block (#427)
Browse files Browse the repository at this point in the history
Co-authored-by: Marco Ieni <[email protected]>
  • Loading branch information
detoxifiedplant and marcoieni authored Jan 21, 2025
1 parent 1fdd141 commit f4daf57
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/patterns/structural/compose-structs.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pattern often reveals smaller units of functionality.
Here is a contrived example of where the borrow checker foils us in our plan to
use a struct:

```rust
```rust,ignore
struct Database {
connection_string: String,
timeout: u32,
Expand All @@ -38,12 +38,22 @@ fn main() {
};
let connection_string = &mut db.connection_string;
print_database(&db); // Immutable borrow of `db` happens here
// *connection_string = "new string".to_string(); // Mutable borrow is used
// here
print_database(&db);
*connection_string = "new string".to_string();
}
```

The compiler throws following errors:

```ignore
let connection_string = &mut db.connection_string;
------------------------- mutable borrow occurs here
print_database(&db);
^^^ immutable borrow occurs here
*connection_string = "new string".to_string();
------------------ mutable borrow later used here
```

We can apply this design pattern and refactor `Database` into three smaller
structs, thus solving the borrow checking issue:

Expand Down

0 comments on commit f4daf57

Please sign in to comment.