Derive Macro bevy_internal::prelude::DerefMut

source ·
#[derive(DerefMut)]
{
    // Attributes available to this derive:
    #[deref]
}
Expand description

Implements DerefMut for structs. This is especially useful when utilizing the newtype pattern.

For single-field structs, the implementation automatically uses that field. For multi-field structs, you must specify which field to use with the #[deref] attribute.

DerefMut requires a Deref implementation. You can implement it manually or use Bevy’s derive macro for convenience.

Example

Tuple Structs

Using a single-field struct:

use bevy_derive::{Deref, DerefMut};

#[derive(Deref, DerefMut)]
struct MyNewtype(String);

let mut foo = MyNewtype(String::from("Hello"));
foo.push_str(" World!");
assert_eq!("Hello World!", *foo);

Using a multi-field struct:

use bevy_derive::{Deref, DerefMut};

#[derive(Deref, DerefMut)]
struct MyStruct<T>(#[deref] String, PhantomData<T>);

let mut foo = MyStruct(String::from("Hello"), PhantomData::<usize>);
foo.push_str(" World!");
assert_eq!("Hello World!", *foo);

Named Structs

Using a single-field struct:

use bevy_derive::{Deref, DerefMut};

#[derive(Deref, DerefMut)]
struct MyStruct {
  value: String,
}

let mut foo = MyStruct {
  value: String::from("Hello")
};
foo.push_str(" World!");
assert_eq!("Hello World!", *foo);

Using a multi-field struct:

use bevy_derive::{Deref, DerefMut};

#[derive(Deref, DerefMut)]
struct MyStruct<T> {
  #[deref]
  value: String,
  _phantom: PhantomData<T>,
}

let mut foo = MyStruct {
  value:String::from("Hello"),
  _phantom:PhantomData::<usize>
};
foo.push_str(" World!");
assert_eq!("Hello World!", *foo);