Skip to content

Instantly share code, notes, and snippets.

@hami9x
Last active November 11, 2018 19:22
Show Gist options
  • Save hami9x/f218761cced412d96533f6e3fd375ef9 to your computer and use it in GitHub Desktop.
Save hami9x/f218761cced412d96533f6e3fd375ef9 to your computer and use it in GitHub Desktop.
Traits and struct embedding in Chi
trait Animal {
int get_id();
void talk() {}
}
struct AnimalBase {
Animal animal...;
int id;
void new(int id) {
this.id = id;
}
int get_id() {
return this.id;
}
};
struct Sheep {
AnimalBase animal...;
void new(int id) {
this.animal = {id};
}
void talk() {
printf("baaaaahh {}\n", this.get_id());
}
};
struct Dog {
AnimalBase animal...;
void new(int id) {
this.animal = {id};
}
int get_id() {
return -this.animal.id;
}
void talk() {
printf("wuff wuff {}\n", this.get_id());
}
};
struct Cat {
Animal animal...;
int get_id() {
return 0;
}
void talk() {
printf("meeoooww {}\n", this.get_id());
}
};
int main() {
Cat cat = {};
Animal animal = &cat;
animal.talk();
Sheep sheep = {1};
Sheep sheep2 = {2};
animal = &sheep;
animal.talk();
animal = &sheep2;
animal.talk();
Dog dog = {3};
animal = &dog;
animal.talk();
return 0;
}
meeoooww 0
baaaaahh 1
baaaaahh 2
wuff wuff -3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment