Eziz Durdyyev
Eziz Durdyyev

Reputation: 1158

Pointers as function arguments when implementing a structure

Why there is a & symbol before self in the full_name() function but there isn't any in the to_tuple() function? When I look at them, the usage of self is similar in both function, but why use &. Also when I add & to to_tuple() or delete it from full_name() it would throw an error. Can someone explain it?

fn full_name(&self) -> String {
    format!("{} {}", self.first_name, self.last_name)
}

fn to_tuple(self) -> (String, String) {
    (self.first_name, self.last_name)
}

Upvotes: 1

Views: 63

Answers (1)

user2722968
user2722968

Reputation: 16535

full_name does not consume self, it uses a reference via &self: The members are only used via references as arguments to format!(), so a reference suffices.

to_tuple (as the name to_... suggests) consumes self: It moves the members from self into the returned tuple. Since the original self is no longer valid memory after the move (self no longer owns the memory), it has to be consumed, hence a move via self.

You can change full_name to use self, that is move ownership. This would become unhandy, though, as calling the function would consume the struct without the need to.

to_tuple could be changed to not consume self, yet it would need to .clone() (make a copy) of the members, which is costly.

Upvotes: 3

Related Questions