@@ -1,13 +1,13 @@
|
||||
# Copying values, pt. 1
|
||||
|
||||
In the previous chapter we introduced ownership and borrowing.
|
||||
In the previous chapter we introduced ownership and borrowing.\
|
||||
We stated, in particular, that:
|
||||
|
||||
- Every value in Rust has a single owner at any given time.
|
||||
- When a function takes ownership of a value ("it consumes it"), the caller can't use that value anymore.
|
||||
|
||||
These restrictions can be somewhat limiting.
|
||||
Sometimes we might have to call a function that takes ownership of a value, but we still need to use
|
||||
These restrictions can be somewhat limiting.\
|
||||
Sometimes we might have to call a function that takes ownership of a value, but we still need to use
|
||||
that value afterward.
|
||||
|
||||
```rust
|
||||
@@ -49,8 +49,8 @@ fn example() {
|
||||
}
|
||||
```
|
||||
|
||||
Instead of giving ownership of `s` to `consumer`, we create a new `String` (by cloning `s`) and give
|
||||
that to `consumer` instead.
|
||||
Instead of giving ownership of `s` to `consumer`, we create a new `String` (by cloning `s`) and give
|
||||
that to `consumer` instead.\
|
||||
`s` remains valid and usable after the call to `consumer`.
|
||||
|
||||
## In memory
|
||||
@@ -92,7 +92,7 @@ If you're coming from a language like Java, you can think of `clone` as a way to
|
||||
|
||||
## Implementing `Clone`
|
||||
|
||||
To make a type `Clone`-able, we have to implement the `Clone` trait for it.
|
||||
To make a type `Clone`-able, we have to implement the `Clone` trait for it.\
|
||||
You almost always implement `Clone` by deriving it:
|
||||
|
||||
```rust
|
||||
@@ -103,7 +103,7 @@ struct MyType {
|
||||
```
|
||||
|
||||
The compiler implements `Clone` for `MyType` as you would expect: it clones each field of `MyType` individually and
|
||||
then constructs a new `MyType` instance using the cloned fields.
|
||||
then constructs a new `MyType` instance using the cloned fields.\
|
||||
Remember that you can use `cargo expand` (or your IDE) to explore the code generated by `derive` macros.
|
||||
|
||||
## References
|
||||
|
||||
Reference in New Issue
Block a user