aboutsummaryrefslogtreecommitdiff
path: root/tour/traits.sloth
blob: 80319decd0bfcdd82a72c9eef41017c608b58c3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Much like Rust's traits or Haskell's type classes sloth uses a trait system for
# polymorphism. 
trait BasicTrait {
    fn add() -> i32;
}

trait AddAssign: Add {
    fn add_assign(value: i32, rhs: i32) -> i32;
}

trait Add {
    fn add(lhs: i32, rhs: i32) -> i32;

    default impl AddAssign {
        fn add_assign(value: i32, rhs: i32) -> i32 {
            return add(value, rhs);
        }
    }
}

# In order to make implementing traits easier you can automatically derive traits.
# Types will implicitly derive from Debug, Copy, Eq and Ord if possible.
type Person = {
    name: String,
    age: i32,
    hobbies: Set<String>,
};

# You can easily derive from more traits using the `derive` keyword.
type Person derives Serialize, Deserialize = {
    name: String,
    age: i32,
    hobbies: Set<String>,
};