1
votes

Here is a link to a playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1e82dcd3d4b7d8af89c5c00597d2d938

I am a newbie learning rust and trying to simply update a mutable vector on a struct.

struct Friend<'a> {
    name: &'a str
}

impl <'a> Friend<'a> {
    fn new(name: &'a str) ->  Self { Self { name } }    
}


struct FriendsList<'a> {
    name: &'a str,
    friends: Vec<Friend<'a>>
}

impl <'a> FriendsList<'a> {
    fn new(name: &'a str, friends: Vec<Friend<'a>>) -> Self { Self { name, friends } }
    fn add_new_friend(&self, friend: Friend) {
        // how to make this work?
        todo!()
        // self.friends.push(friend)
    }
}

fn main() {
    let friends_list = FriendsList::new("George",
        vec![
            Friend::new("bob"), 
            Friend::new("bobby"), 
            Friend::new("bobbo")
        ]
    );
}

specifically how do I make this fn add_new_friend(&self, friend: Friend) method work? That is, push a new element to field friends on the FriendsList struct. Is there a more idiomatic approach? When I try making things mutable, I get a whole bunch of errors I am not sure how to fix...

1
&self -> &mut selfRabbid76
You probably want to make Friend contain a String rather than &str - you'll just have a much more enjoyable time with experimenting. &str is also a valid choice, but for more specific circumstances. You can also use &'static str which will work just fine for strings coming from string literals, and the 'a lifetime from infect all your structs.user4815162342
That's a good tip, thanks!codingdraculasbrain

1 Answers

1
votes

You have to borrow self mutably:

impl <'a> FriendsList<'a> {
    // [...]

    fn add_new_friend(&mut self, friend: Friend<'a>) {
        self.friends.push(friend)
    }
}