Last active
April 5, 2023 15:57
-
-
Save marler8997/28a538522bd8c7365f065ea1b0f7af10 to your computer and use it in GitHub Desktop.
Opaque Type Heirarchies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub const Animal = *opaque {}; | |
// allow opaque to take a type as a parent | |
pub const Dog = *opaque(Animal) {}; | |
pub const Cat = *opaque {}; | |
const some_library = struct { | |
pub extern fn makeDog() Dog; | |
pub extern fn bark(Dog) void; | |
pub extern fn pet(Animal) void; | |
}; | |
pub fn main() void { | |
const dog = some_library.makeDog(); | |
some_library.bark(dog); | |
// no need to cast because a Dog was defined as an Animal | |
some_library.pet(dog); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub const Animal = *opaque {}; | |
pub const Dog = *opaque { | |
pub fn asAnimal(self: Dog) Animal { | |
return @ptrCast(Animal, self); | |
} | |
}; | |
pub const Cat = *opaque {}; | |
const some_library = struct { | |
pub extern fn makeDog() Dog; | |
pub extern fn bark(Dog) void; | |
pub extern fn pet(Animal) void; | |
}; | |
pub fn main() void { | |
const dog = some_library.makeDog(); | |
some_library.bark(dog); | |
some_library.pet(dog.asAnimal()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment