#Is there any way to refactor this?

1 messages · Page 1 of 1 (latest)

glossy trench
#
    pub fn add_player(&mut self,pl_name: &str)->  Option<&Player> {
        let pl = Player::new(pl_name);
        self.players.insert(String::from(pl_name), pl);
        self.players.get(&String::from(pl_name))
night sky
#

yes -- it depends on what you would like your overall semantics to be

#

because insert returns a value

#
pub fn insert(&mut self, k: K, v: V) -> Option<V>

Inserts a key-value pair into the map.

If the map did not have this key present, None is returned.

If the map did have this key present, the value is updated, and the old value is returned. The key is not updated, though; this matters for types that can be == without being identical.```
#

if you wanted to follow those semantics, you could do: ```rust
pub fn add_player(&mut self,pl_name: &str)-> Option<&Player> {
self.players.insert(pl_name, Player::new(pl_name))
}

#

but that is different semantics from your original function -- it looks like your function returns the player which was added. It does not look like there is a way for the original to return None. Thus, the return value of Option is unnecessary

#

you might want to call it update_player, or something like that

#

update_player or create_and_insert_player

#

idk

#

your call

#

it is really just a wrapper around insert, so keeping the name insert might be helpful

#

if you call it add_player, maybe it is a good idea to check to see if you are overwriting an existing player

#

depending on whether you want that to be allowed

#

maybe you dont want to overwrite an existing player, idk

#

gtg

#

good luck 🙏

shrewd zinc
#

entry() and or_insert_with_key() may be of use to you...

#

So the player initialisation is only run lazily, if there isn't a pre-existing one.

#

And, if you need to create an owned string from the method argument, it may be preferable to explicitly call for that as a parameter, making the cost clear to the method caller...

glossy trench
#

thanks dudes

shrewd zinc
#

FYI: entry() will account for that,

fierce charm
#

There is also the nightly feature get_or_insert which has the desired functionality

shrewd zinc
#

It lazily runs the insert...?

fierce charm
#

Ah I'm not sure

#

But there might be get_or_insert_with

shrewd zinc
#

I couldn't see either documented,

fierce charm
#

My bad