Skip to main content

Inherits

Trait Inherits 

Source
pub unsafe trait Inherits<B> { }
Expand description

Marks Self as deriving from B, so a pointer to a Self is also a valid pointer to its B.

Generated bindings implement it for every ancestor of a class, and give the class Deref and DerefMut to its direct base so references reach base fields and coerce to base references. For raw pointers, use Upcast::upcast.

§Safety

Self must have a defined layout (repr(C) or repr(transparent)) with a B at offset 0, and every valid Self must hold a valid B there.

§Examples

use imping_runtime::{Inherits, Upcast};

#[repr(C)]
struct Entity { health: i32 }
#[repr(C)]
struct Player { base: Entity, level: i32 }

// SAFETY: `Player` is `repr(C)` and starts with its `Entity`.
unsafe impl Inherits<Entity> for Player {}

fn heal(entity: *mut Entity) {
    // SAFETY: the caller passes a live entity.
    unsafe { (*entity).health = 100 };
}

let mut player = Player { base: Entity { health: 1 }, level: 3 };
let pointer: *mut Player = &mut player;
heal(pointer.upcast());
assert_eq!(player.base.health, 100);

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§