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

Chapter 8.1: Explanation for listing 8-7 seems to be incorrect #1785

Closed
pszpetkowski opened this issue Jan 24, 2019 · 4 comments · Fixed by #2357
Closed

Chapter 8.1: Explanation for listing 8-7 seems to be incorrect #1785

pszpetkowski opened this issue Jan 24, 2019 · 4 comments · Fixed by #2357
Labels

Comments

@pszpetkowski
Copy link

Recall the rule that states you can’t have mutable and immutable references in the same scope. That rule applies in Listing 8-7, where we hold an immutable reference to the first element in a vector and try to add an element to the end, which won’t work.

It's quite interesting, because I've tried it out with Rust 1.32 and pushing new element to vector seems to work just fine:

let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0];
println!("v: {:?}", v);
v.push(6);
println!("v: {:?}", v);

Output:

v: [1, 2, 3, 4, 5]
v: [1, 2, 3, 4, 5, 6]

In my case it's printing variable first after pushing to vector that causes the error.

@eddyp
Copy link
Contributor

eddyp commented Jan 24, 2019

@piotr-szpetkowski I think this is due to non lexical lifetimes and the fact you don't try to use 'first' after the push and the same code will not compile if you don't use 2018 edition semantics.

Can you try removing the edition field from Cargo.toml to check?

@pszpetkowski
Copy link
Author

@eddyp Yeah, it looks like you're right. In case of 2015 edition it fails on push with cannot borrow 'v' as mutable because it is also borrowed as immutable

@eddyp
Copy link
Contributor

eddyp commented Jan 24, 2019

@piotr-szpetkowski OK, going back to 2018, I think it will fail with non lexical lifetimes if you try to use 'first', say by println!("first = {}", first) after the v.push. Can try that, too?

@pszpetkowski
Copy link
Author

@eddyp Sure, I've already tried that before when I've been experimenting with the listing from the book and it does cause an error which is presented in Listing 8.7 of the book.

So, basically it seems like Listing has been updated for the 2018 edition, but the explanation hasn't.

steveklabnik added a commit that referenced this issue Jun 5, 2020
It's not just that we add something to the end, it's also that we need
to hold onto the reference.

FIxes #1785
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants