Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement GenericWriteStorage::get_mut_or_default #561

Closed
JaniM opened this issue Mar 7, 2019 · 0 comments
Closed

Implement GenericWriteStorage::get_mut_or_default #561

JaniM opened this issue Mar 7, 2019 · 0 comments

Comments

@JaniM
Copy link
Contributor

JaniM commented Mar 7, 2019

Description

Implement GenericWriteStorage::get_mut_or_default, which either fetches an existing component, or calls Default::default on the component type, inserts the newly created struct in to the storage, and returns a mutable reference to it.

This can never fail.

Motivation

I found myself writing a lot of code along the lines of

if let Some(stun) = data.stun.get_mut(entity) {
    stun.time += 1;
} else {
    data.stun.insert(entity, Stun { time: 1 }).unwrap();
}

Verbose, and extremely repetitive. The new function offers a shorthand:

data.stun.get_mut_or_default(entity).time += 1;

Drawbacks

An extra function to maintain. However, it builds on the existing methods of GenericWriteStorage, so the maintenance impact should be near zero.`

Unresolved questions


Opened a PR for this.

bors bot added a commit that referenced this issue Mar 29, 2019
563: Optionized get_mut_or_default r=torkleyy a=JaniM

Fixes #561
Alternative to #562 . Implements an Option API instead of panicking if the entity is dead

I have no idea how I managed to mess up the branch name.



Co-authored-by: Jani Mustonen <[email protected]>
@bors bors bot closed this as completed in #563 Mar 29, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant