#Is there any way to refactor this?
1 messages · Page 1 of 1 (latest)
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 🙏
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...
I didn't notice that
thanks dudes
FYI: entry() will account for that,
There is also the nightly feature get_or_insert which has the desired functionality
It lazily runs the insert...?
I couldn't see either documented,
My bad