Rust in Action Notes Chapter 4 Life Cycle, Ownership, Borrowing

  1. Chapter 4 uses an example of planetary communication to illustrate the whole theme. The main characters are Ground station and CubeSat, both of which have different states and can send messages to each other;

  2. Rust has a type safety (type safety) mechanism to check the type and return value of the function. If a custom type (declared with struct) contains non-built-in types (such as i32, bool, etc., which implement the copy feature), it will trigger the move (move) semantics when used as a parameter in the function, and its ownership is moved to the formal parameter of the function. Figure 4.2 gives a very intuitive process of ownership transfer;Figure 4.2

  3. Codes 4.5 and 4.6 show the differences between built-in types with copy semantics and general types with move semantics. One can be compiled and the other cannot. The main difference lies in whether the copy trait is implemented;

  4. The owner (owner) has the ownership (onwership) of certain values. Once the life cycle of the owner is reached (such as reaching the end of the code block or other reasons), their destructor (destructor) will be called. The destructor will delete all references (references) related to it and release the memory. Most of the destructors will be called implicitly, which is done by the compiler. It needs to be used in the memory allocation implemented by the unsafe block;

  5. There are two ways to transfer ownership, one is variable binding, which letbinds an object to a variable through a keyword; the other is through a function, which can be a function parameter or a return value, see page 115 for details;

  6. There are 4 useful habits to solve the ownership problem, a. If complete ownership is not necessary, you can use references (references), see Section 4.5.1 for details; b. For values ​​with Copy characteristics, you can directly copy, see Section 4.5.2 for details; c. Refactor the code to minimize long-lived objects, see Section 4.5.3 for details; Section 4.5.4;

  7. CloneThe difference between and Copyis compared in detail in Table 4.2 below;Table 4.2

  8. std::rc::Rc<T>There are three reasons why Copy is not used. a. The premise of Copy is to only introduce a small performance cost, that is, only when the data is small (such as digital i32, i64, etc.), the performance loss caused by using Copy is minimal; b. Copy is a bit-level copy, and the processing of references may not be accurate; c. Some types overload Clone.

  9. Internal variability can be achieved through it Rc<RefCell<T>>, and at the same time, a little runtime overhead is introduced; when the cost of using Clone is too high, it can be used Rc<RefCell<T>>as an alternative, Rc<RefCell<T>>which is not multi-thread safe; see page132 for details;

Guess you like

Origin blog.csdn.net/Mint2yx4/article/details/131164511