bevy/crates/bevy_reflect/src/impls
Gino Valente 229d6c686f bevy_reflect: Simplify take-or-else-from_reflect operation (#6566)
# Objective

There are times where we want to simply take an owned `dyn Reflect` and cast it to a type `T`.

Currently, this involves doing:

```rust
let value = value.take::<T>().unwrap_or_else(|value| {
  T::from_reflect(&*value).unwrap_or_else(|| {
    panic!(
      "expected value of type {} to convert to type {}.",
      value.type_name(),
      std::any::type_name::<T>()
    )
  })
});
```

This is a common operation that could be easily be simplified.

## Solution

Add the `FromReflect::take_from_reflect` method. This first tries to `take` the value, calling `from_reflect` iff that fails.

```rust
let value = T::take_from_reflect(value).unwrap_or_else(|value| {
  panic!(
    "expected value of type {} to convert to type {}.",
    value.type_name(),
    std::any::type_name::<T>()
  )
});
```

Based on suggestion from @soqb on [Discord](https://discord.com/channels/691052431525675048/1002362493634629796/1041046880316043374).

---

## Changelog

- Add `FromReflect::take_from_reflect` method
2023-01-11 16:25:37 +00:00
..
glam.rs Make proc macros hygienic in bevy_reflect_derive (#6752) 2022-12-05 23:39:44 +00:00
rect.rs Make proc macros hygienic in bevy_reflect_derive (#6752) 2022-12-05 23:39:44 +00:00
smallvec.rs reflect: add insert and remove methods to List (#7063) 2023-01-09 19:47:07 +00:00
std.rs bevy_reflect: Simplify take-or-else-from_reflect operation (#6566) 2023-01-11 16:25:37 +00:00