Created
January 6, 2026 18:36
-
-
Save ildar/e5e9676f62a6b96ef2ac7b81be74ca12 to your computer and use it in GitHub Desktop.
Teal implementation of https://doc.rust-lang.org/rust-by-example/trait.html
This file contains hidden or 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
| local interface Animal | |
| -- Associated function signature; `Self` refers to the implementor type. | |
| new: function(string): self | |
| -- Method signatures; these will return a string. | |
| name: function(self): string | |
| noise: function(self): string | |
| talk: function(self) | |
| end | |
| local record Sheep is Animal | |
| _naked: boolean | |
| _name: string | |
| end | |
| -- impl Sheep | |
| function Sheep:is_naked(): boolean | |
| return self._naked | |
| end | |
| function Sheep:shear() | |
| if self:is_naked() then | |
| -- Implementor methods can use the implementor's trait methods. | |
| print(self:name(), "is already naked..."); | |
| else | |
| print(self._name, "gets a haircut!"); | |
| self._naked = true; | |
| end | |
| end | |
| -- Implement the `Animal` trait for `Sheep`. | |
| -- impl Animal for Sheep | |
| -- `Self` is the implementor type: `Sheep`. | |
| function Sheep.new(name: string): Sheep | |
| local res: Sheep = { _name=name, _naked=false } | |
| return setmetatable(res, {__index=Sheep}) | |
| end | |
| function Sheep:name(): string | |
| return self._name | |
| end | |
| function Sheep:noise(): string | |
| if self:is_naked() then | |
| return "baaaaah?" | |
| else | |
| return "baaaaah!" | |
| end | |
| end | |
| function Sheep:talk() | |
| -- For example, we can add some quiet contemplation. | |
| print(self._name, "pauses briefly... ", self:noise()); | |
| end | |
| -- fn main() | |
| -- Type annotation is necessary in this case. | |
| local dolly = Sheep.new("Dolly") | |
| dolly:talk(); | |
| dolly:shear(); | |
| dolly:talk(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment