Think of &mut T means “exclusive (mutable) access” and &T means “no one has mutable access”. Let’s assume is_fed is a very expensive operation and in Rust we have the second rule, that when I have a borrow (no matter if mutable or immutable) it’s not possible for any other component to have a mutable borrow, so reading is_fed once could be cached for the whole lifetime of the FeedChecker. That is not an issue here, because Rust has other concepts for data access with multiple threads, but it is going in the same direction. Now, why on earth should the last example be a problem? You may have heard the term “multiple readers or one writer” in a multi-threaded context. Having the immutable borrow living in the FeedChecker will overlap the mutable borrow for feeding the cat, which then break the second borrow rule.īorrow-checker issues - Code smell or bug? We pass an immutable borrow to the FeedChecker that it can check the cat later and we then also mutate the cat, because you can read cat.feed() same like Cat::feed(&mut cat), because feed takes a &mut self, so it creates a mutable borrow of cat. That also means reading any code will clearly show what is happening regarding ownership.Įnter fullscreen mode Exit fullscreen mode Rust on the other hand has a strict ownership concept. Thus static code analysis tools may help you, but at some point even they can’t. The problem is that the language can’t enforce them. Languages without garbage collector like C++ provide concepts and conventions for ownership. ![]() exclusive mutable or shared immutable borrows: borrowed data is exclusive mutable or shared immutable.Coming from any other language it’s very likely that the way one wrote code will simply not work with Rust, although being a “good developer”. Having some native development background makes it a bit easier to jump into Rust, but there is also a need to change the mindset. ![]() This post will give a small overview of the problem and how to fix them or better, how to prevent them. A thing that is often quite time-consuming writing Rust code is the fight with the borrow-checker.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |