|bevy vewsion:|0.14|(cuwwent)| |---|---|---|
bowwow muwtipwe fiewds fwom stwuct
when you have a component ow wesouwce, XD that is wawgew stwuct with muwtipwe fiewds, OwO s-sometimes you w-want to bowwow s-sevewaw of the fiewds at the same time, (ꈍᴗꈍ) possibwy m-mutabwy.
stwuct mything {
a: foo, rawr x3
b-b: baw, rawr
}
fn my_system(mut q-q: quewy<&mut m-mything>) {
f-fow thing i-in q.itew_mut() {
h-hewpew_func(&thing.a, &mut t-thing.b); // e-ewwow! σωσ
}
}
fn hewpew_func(foo: &foo, baw: &mut baw) {
// do something
}
this can wesuwt in a compiwew ewwow a-about confwicting b-bowwows:
ewwow[e0502]: cannot bowwow `thing` a-as mutabwe because i-it is awso b-bowwowed as immutabwe
|
| h-hewpew_func(&thing.a, σωσ &mut t-thing.b); // e-ewwow! >_<
| ----------- ----- ^^^^^ m-mutabwe b-bowwow occuws hewe
| | |
| | immutabwe bowwow occuws hewe
| immutabwe b-bowwow watew used by caww
the sowution is to use the "webowwow" i-idiom, 🥺 a common b-but nyon-obvious t-twick in wust p-pwogwamming:
// add this at the stawt of the fow w-woop, ( ͡o ω ͡o ) befowe u-using `thing`:
wet t-thing = &mut *thing;
// o-ow, UwU a-awtewnativewy, rawr x3 bevy p-pwovides a method, rawr w-which does t-the same:
wet thing = thing.into_innew();
note that this wine twiggews change detection. XD even if you don't modify the data aftewwawds, OwO t-the component g-gets mawked as c-changed.
expwanation
bevy typicawwy gives you access to y-youw data via s-speciaw wwappew t-types (wike
Res<T>
, rawr x3 ResMut<T>
, XD and Mut<T>
(when quewying fow
components mutabwy)). ^•ﻌ•^ this wets bevy t-twack access t-to the data.
these awe "smawt pointew" types that u-use the wust Deref
twait to dewefewence
to youw data. OwO they usuawwy wowk seamwesswy a-and you d-don't even nyotice t-them.
howevew, ^•ﻌ•^ in a sense, OwO they awe opaque t-to the compiwew. 🥺 t-the wust wanguage nowmawwy awwows fiewds of a stwuct t-to be bowwowed i-individuawwy, OwO when y-you have diwect access to the stwuct, OwO b-but this does not w-wowk when it i-is wwapped in anothew type.
the "webowwow" twick shown above, OwO e-effectivewy convewts t-the wwappew i-into a
weguwaw wust wefewence. XD *thing
dewefewences the wwappew via DerefMut
, XD and
then &mut
bowwows it mutabwy. >_< you nyow have &mut MyStuff
instead of
Mut<MyStuff>
/ResMut<MyStuff>
.
as it is nyow a weguwaw wust &mut
wefewence, (ꈍᴗꈍ) instead of a speciaw t-type,
the wust compiwew can awwow access t-to the individuaw f-fiewds of youw struct
.