Modify enum through &mut self
⚓ Rust 📅 2026-03-04 👤 surdeus 👁️ 1Hi !
I'm facing a problem I have never seen. I fail to reproduce it with minimal code reproduction. So, there is a part of the code below (you can find the whole source code here).
pub trait Physic: Material {
// [...]
fn set_position(&mut self, value: [f32; 2]);
// [...]
}
#[derive(Archive, Deserialize, Serialize, Clone, Debug, PartialEq, Constructor)]
#[rkyv(compare(PartialEq), derive(Debug))]
pub struct Bullet {
pub position: [f32; 2],
pub tile: TileXy,
pub region: RegionXy,
pub forces: Vec<Force>,
}
#[derive(Archive, Deserialize, Serialize, Clone, Debug, PartialEq)]
#[rkyv(compare(PartialEq), derive(Debug))]
pub enum Projectile {
Bullet(Bullet),
}
impl Physic for &Projectile {
// [...]
fn set_position(&mut self, value: [f32; 2]) {
match self {
Projectile::Bullet(bullet) => bullet.position = value,
}
}
// [...]
}
Error is:
error[E0594]: cannot assign to `bullet.position`, which is behind a `&` reference
--> crates/oc_projectile/src/lib.rs:68:43
|
68 | Projectile::Bullet(bullet) => bullet.position = value,
| ^^^^^^^^^^^^^^^^^^^^^^^ `bullet` is a `&` reference, so it cannot be written to
As I can see, bullet here is &Bullet. But, I expect &mut Bullet as I match from &mut self. I don't understand ...
Thanks in advance !
4 posts - 3 participants
🏷️ Rust_feed