Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot move out of *** which is behind a shared reference [duplicate]

Tags:

rust

I'm learning Rust and I've a question regarding how to pass a reference of a variable to a funcion and make a cascade call with it.

I'm facing the error indicated in the code bellow:

struct User {
    name: String,
    address: String
}

// Argument "user" is intentionaly a reference to User struct;
//
fn func1(user: &User) {
    println!("func1: {}, {}", user.name, user.address);

    // error[E0507]: cannot move out of `*user` which is behind a shared reference
    //
    func2(*user);
}

// Argument "user" is intentionaly an instance of User struct;
//
fn func2(user: User) {
    println!("func2: {}, {}", user.name, user.address);
}

fn main() {
    let user = User {
        name: String::from("George"),
        address: String::from("Main Street")
    };

    func1(&user);
}

Why can't I do that? What I supposed to do?

I think cloning the User object is not a option. Imagine if instead of this simple structure we have a super structure that could occupy several MBytes?

like image 491
nermind Avatar asked May 25 '20 03:05

nermind


1 Answers

fn func1(user: &User) is a function that borrows an existing User object, promising not to modify it. fn func2(user: User) is a function that takes ownership of an object and never gives it back.

Rust is preventing you from doing something silly. Having func1 call func2 is like promising me you'll just borrow my class notes for a quick read and then passing it to a friend who then runs off and keeps them. There's no way you can give me back my original.

The solution is either

  1. Make func2 take a reference too. This is equivalent to making your friend promise to give back the notes to you. You can then return them to me.
  2. Clone the object before passing to func2. This is equivalent to you making a copy of the notes and letting your friend run off with your copy - then giving me back my original.
like image 78
Michael Anderson Avatar answered Nov 03 '22 21:11

Michael Anderson