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

Ownership Guide: Borrowing example doesn't work with previously introduced main function #19924

Closed
lgrahl opened this issue Dec 16, 2014 · 4 comments · Fixed by #21029
Closed

Comments

@lgrahl
Copy link

lgrahl commented Dec 16, 2014

In the ownership guide is an example for borrowing that doesn't work with the previously introduced main function. I guess this is because cross-borrowing is not allowed anymore?

fn main() {
    let x = box 5i;
    add_one(x);
    println!("{}", x);
}
fn add_one(num: &mut int) {
    *num += 1;
}

See: https://github.com/rust-lang/rust/blob/master/src/doc/guide-ownership.md#borrowing

@steveklabnik
Copy link
Member

Yes. Do you have an idea of how to fix this? I'm not sure what makes the most sense, exactly.

@lgrahl
Copy link
Author

lgrahl commented Dec 17, 2014

Well, yeah... I've found a way to borrow the box but it's extremely ugly. Prepare yourself...

fn main() {
    let mut x = box 5i;
    add_one(&mut x);
    println!("{}", x);
}

fn add_one(num: &mut Box<int>) {
    **num += 1;
}

No, honestly, this can't be it. I'd rather hit myself with an axe.

There are a few RFCs out there which seem to address this problem, but I'm not sure whether they address mutable references as well. Maybe you could have a look. I'm not even sure if these RFCs are related to this problem.

@tomjakubowski
Copy link
Contributor

Try this:

fn main() {
    let mut x = box 5i;
    add_one(&mut *x);
    println!("{}", x);
}

fn add_one(num: &mut int) {
    *num += 1;
}

(edit: I first submitted this post by mistake with a paste from a stale clipboard. Updated to reflect the necessary changes to the snippet)

@lgrahl
Copy link
Author

lgrahl commented Dec 17, 2014

Yeah, that works. Thanks!

steveklabnik added a commit to steveklabnik/rust that referenced this issue Jan 12, 2015
alexcrichton added a commit to alexcrichton/rust that referenced this issue Jan 15, 2015
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 a pull request may close this issue.

3 participants