Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions lessons/en/chapter_5.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,30 @@
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=struct%20Bar%20%7B%0A%20%20%20%20x%3A%20i32%2C%0A%7D%0A%0Astruct%20Foo%20%7B%0A%20%20%20%20bar%3A%20Bar%2C%0A%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20foo%20%3D%20Foo%20%7B%20bar%3A%20Bar%20%7B%20x%3A%2042%20%7D%20%7D%3B%0A%20%20%20%20println!(%22%7B%7D%22%2C%20foo.bar.x)%3B%0A%20%20%20%20%2F%2F%20foo%20is%20dropped%20first%0A%20%20%20%20%2F%2F%20then%20foo.bar%20is%20dropped%0A%7D%0A
- title: Moving Ownership
content_markdown: >
When an owner is passed as an argument to a function, ownership is moved to
the function parameter.
When an owner is passed as an argument to a function, ownership of the
value is moved to the function parameter. This means that the original
variable in the calling function loses access to the value and can no
longer be used.


After a **move** the variable in the original function can no longer be
used.
After a move, the original variable becomes invalid, and attempting
to use it will result in a compiler error. This ensures memory safety
by preventing use-after-move issues.


Memory details:

* During a **move** the stack memory of the owners value is copied to the
function call's parameter stack memory.
function call's parameter stack memory. For heap-allocated data (e.g., owned
types like String or Vec), the pointer to the heap memory is moved, but the
actual data on the heap is not copied. Instead, the ownership of the heap
memory is transferred.


When values are dropped:
* A value is dropped (cleaned up) when it goes out of scope. For function
parameters, this occurs at the end of the function's execution.

code: >-
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=struct%20Foo%20%7B%0A%20%20%20%20x%3A%20i32%2C%0A%7D%0A%0Afn%20do_something(f%3A%20Foo)%20%7B%0A%20%20%20%20println!(%22%7B%7D%22%2C%20f.x)%3B%0A%20%20%20%20%2F%2F%20f%20is%20dropped%20here%0A%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20foo%20%3D%20Foo%20%7B%20x%3A%2042%20%7D%3B%0A%20%20%20%20%2F%2F%20foo%20is%20moved%20to%20do_something%0A%20%20%20%20do_something(foo)%3B%0A%20%20%20%20%2F%2F%20foo%20can%20no%20longer%20be%20used%0A%7D%0A
- title: Returning Ownership
Expand Down