Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better example for ownership transfer using String #68

Merged
merged 2 commits into from
May 28, 2024

Conversation

keshav-c
Copy link
Contributor

I think the ownership transfer bits can use a better example.

The value 42 is just copied into the new variable, so this example does demonstrate the functioning of the borrow checker.

let a = 42;
let b = a;
println!("a is {}, b is {}", a, b);

Outputs

a is 42, b is 42

But on changing to a String value

let a = String::from("hello");
let b = a;
println!("a is {}, b is {}", a, b);

We get a better demonstration

   Compiling my-project v0.1.0 (/Users/keshav/my-project)
error[E0382]: borrow of moved value: `a`
 --> src/main.rs:8:34
  |
6 |     let a = String::from("hello");
  |         - move occurs because `a` has type `String`, which does not implement the `Copy` trait
7 |     let b = a;
  |             - value moved here
8 |     println!("a is {}, b is {}", a, b);
  |                                  ^ value borrowed here after move

I really like your approach to learning Rust. I crashed out of reading the book 2 times. But I think it's much better as a companion to this way of learning

@LukeMathWalker
Copy link
Collaborator

I agree, a String is a more fitting example. Thank you!

@LukeMathWalker LukeMathWalker merged commit d77272a into mainmatter:main May 28, 2024
2 checks passed
@keshav-c keshav-c deleted the ownership-transfer-example branch May 29, 2024 01:44
hongyanca pushed a commit to hongyanca/100-exercises-to-learn-rust that referenced this pull request May 29, 2024
* Better example for ownership transfer using String

* Update book/src/03_ticket_v1/06_ownership.md

---------

Co-authored-by: Luca Palmieri <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants