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?
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
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.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With