Reading the Rust book, I find the statement in chapter 4:
Each value in Rust has an owner.
I'm getting back to basics here. What is a "value". Is it: a chunk of memory with a type?
Reading the Rust book, I find the statement in chapter 4:
Each value in Rust has an owner.
I'm getting back to basics here. What is a "value". Is it: a chunk of memory with a type?
A value is a sequence of bytes with a type giving some interpretation of those bytes. The chunk of memory, the place, in which the value is stored is distinct from the value itself.
That's a decent definition IMO.
Unsolicited advice time!
There's not really a formal definition of "ownership". It's a somewhat fuzzy concept. Depending on the situation, my preferred ways of thinking about it are:
So the fields of a struct would be owned by the struct, say. Or a value on the stack would be owned by the function. These values could be references; the reference would be owned, but not necessarily the referent. These values could implement Copy
, in which case ownership doesn't necessarily matter.
(Sometimes "owned" is used to mean "meets a 'static
bound", but that doesn't really jive with my mental model.)
And now for some rebuttals or perhaps... increased granularity to the phrasing used in the book.
- Each value in Rust has an owner.
In my mental model, not all values have to be owned. static
values aren't moved or destructed. The same can be true of leaked values.
- There can only be one owner at a time.
[skip forward 11 chapters]
However, there are cases when a single value might have multiple owners.
In other words: shared ownership can be modeled in Rust.
- When the owner goes out of scope, the value will be dropped.
Also when it's overwritten.
I might provide a larger set of "companion notes" for the chapter or sub-chapter later. Just be aware that the book is presenting an approximation to get the gist across. The heap and avoiding dangling pointers are examples of why the ownership and borrowing system are useful, but are not the sole motivations or reasons for them.
The actual problem with that phrase is not the "value", which might be unsharp, but understandable. It is the "owner", which might be a program, process, thread?
I have finally decided to write "In Rust, every value has a variable that is its owner." which should be easier to understand. Of course the term variable is defined earlier.
"Variables associate names with data stored in memory."