Last active
November 11, 2018 19:22
-
-
Save hami9x/f218761cced412d96533f6e3fd375ef9 to your computer and use it in GitHub Desktop.
Traits and struct embedding in Chi
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
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; | |
} |
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
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